Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions WeatherRoutingTool/algorithms/genetic/patcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import logging
import math
import os
import threading
from datetime import datetime
from pathlib import Path

Expand Down Expand Up @@ -41,18 +42,22 @@ def patch(self, src: tuple, dst: tuple):

class SingletonBase(type):
"""
TODO: make this thread-safe
Base class for Singleton implementation of patcher methods.
Thread-safe base class for Singleton implementation of patcher methods.

This is the implementation of a metaclass for those classes for which only a single instance shall be available
during runtime.
during runtime. Uses a lock to ensure thread-safety during instance creation.
"""
_instances = {}
_lock = threading.Lock()

def __call__(cls, *args, **kwargs):
# Double-checked locking pattern for thread-safety
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance
with cls._lock:
# Check again after acquiring the lock
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance

return cls._instances[cls]

Expand Down