########################################################################### # # Copyright (c) 2019-2021 Diality Inc. - All Rights Reserved. # # THIS CODE MAY NOT BE COPIED OR REPRODUCED IN ANY FORM, IN PART OR IN # WHOLE, WITHOUT THE EXPLICIT PERMISSION OF THE COPYRIGHT OWNER. # # @file singleton.py # # @author (last) Quang Nguyen # @date (last) 19-Jul-2021 # @author (original) Peter Lucia # @date (original) 29-Apr-2021 # ############################################################################ from threading import Lock class SingletonMeta(type): """ Thread-safe implementation of Singleton. """ _instances = {} _lock: Lock = Lock() _creation_attempts = 0 """ Synchronizes threads during first access to the Singleton. """ def __call__(cls, *args, **kwargs): """ Possible changes to the value of the `__init__` argument do not affect the returned instance. """ cls._creation_attempts += 1 # TODO: Remove later - keep for debugging # print("CAN interface constructor call counter: {0}".format(cls._creation_attempts)) # First thread acquires the lock with cls._lock: if cls not in cls._instances: instance = super().__call__(*args, **kwargs) cls._instances[cls] = instance return cls._instances[cls]