Singleton_Threadsafe.py 1012 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import functools
  2. import threading
  3. lock = threading.Lock()
  4. def synchronized(lock):
  5. """ Synchronization decorator """
  6. def wrapper(f):
  7. @functools.wraps(f)
  8. def inner_wrapper(*args, **kw):
  9. with lock:
  10. return f(*args, **kw)
  11. return inner_wrapper
  12. return wrapper
  13. class SingletonThreadsafe(type):
  14. _instances = {}
  15. def __call__(cls, *args, **kwargs):
  16. if cls not in cls._instances:
  17. cls._locked_call(*args, **kwargs)
  18. return cls._instances[cls]
  19. @synchronized(lock)
  20. def _locked_call(cls, *args, **kwargs):
  21. if cls not in cls._instances:
  22. cls._instances[cls] = super(SingletonThreadsafe, cls).__call__(*args, **kwargs)
  23. class testClass(metaclass=SingletonThreadsafe):
  24. pass
  25. def __init__(self, message: str = None):
  26. self._message = message
  27. if __name__ == "__main__":
  28. x = testClass('hello')
  29. y = testClass('yellow')
  30. print(x==y)
  31. print(x._message)
  32. print(y._message)