diff --git a/WeatherRoutingTool/algorithms/genetic/patcher.py b/WeatherRoutingTool/algorithms/genetic/patcher.py index c196a01..26dfe67 100644 --- a/WeatherRoutingTool/algorithms/genetic/patcher.py +++ b/WeatherRoutingTool/algorithms/genetic/patcher.py @@ -2,6 +2,7 @@ import logging import math import os +import threading from datetime import datetime from pathlib import Path @@ -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]