使用python写一个线程安全的单例模式
# 使用python写一个线程安全的单例模式 # 参考:https://juejin.cn/post/6844903951624585229 import threading import time def synchronized(func): func.__lock__ = threading.Lock() def lock_func(*args, **kwargs): with func.__lock__: return func(*args, **kwargs) return lock_func class Singleton(object): instance = None @synchronized def __new__(cls, *args, **kwargs): # type kwargs: object if cls.instance is None: time.sleep(0.5) cls.instance = super().__new__(cls) return cls.instance class MyClass(Singleton): def __init__(self, a): self.a = a def check(lst): for i in range(len(lst)): if i > 0 and id(lst[i]) != id(lst[i - 1]): return False return True def test(n): def func(): obj = Singleton(9) print(id(obj)) for i in range(n): thread = threading.Thread(target=func) thread.start() if __name__ == "__main__": test(10) # 31744710112483174471011248 # # 31744710112483174471011248 # 3174471011248 # # 3174471011248 # 3174471011248 # 3174471011248 # 3174471011248 # 3174471011248