fix 单例加锁,防止init方法时间过长导致多次init

This commit is contained in:
thsrite 2024-04-13 17:33:08 +08:00
parent 6a8a946ec8
commit fc65cc3619

View File

@ -1,4 +1,5 @@
import abc
import threading
class Singleton(abc.ABCMeta, type):
@ -7,12 +8,14 @@ class Singleton(abc.ABCMeta, type):
"""
_instances: dict = {}
_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
key = (cls, args, frozenset(kwargs.items()))
if key not in cls._instances:
cls._instances[key] = super().__call__(*args, **kwargs)
return cls._instances[key]
with cls._lock:
if key not in cls._instances:
cls._instances[key] = super().__call__(*args, **kwargs)
return cls._instances[key]
class AbstractSingleton(abc.ABC, metaclass=Singleton):