from functools import wraps
import threading
import time
def Singleton(cls):
instance = {}
lock = threading.Lock() #引入互斥锁,保证线程安全
@wraps(cls) #通过这行代码保留被装饰类的基础信息,如文档字符串等
def wrapper(*args, **kwargs):
with lock:
if cls not in instance:
time.sleep(2)
instance[cls] = cls(*args, **kwargs)
return instance[cls]
return wrapper
@Singleton
class Person: #被装饰的对象
a = 2
def func():
b = Person()
#打印,观察对象的内存地址是否一致
print(b)
if __name__ == "__main__":
#验证多线程时,单例模式是否线程安全
for i in range(5):
t = threading.Thread(target=func)
t.start()