import threading
def sync(func):
func.__lock__ = threading.Lock()
def inner(*args, **kwargs):
with func.__lock__:
return func(*args, **kwargs)
return inner
class Singleton:
__instance = None
@sync
def __new__(cls,*args, **kwargs):
print("New")
if cls.__instance is None:
print("Create")
cls.__instance = super().__new__(cls)
return cls.__instance
else:
return cls.__instance
# 如果没有else返回仍是两个不同的对象,因为打印出来的id不同
def __init__(self):
print("初始化")
self.a = 5
s1 = Singleton()
s2 = Singleton()
# 执行结果
# New
# Create
# 初始化
# New
print(id(s1))
print(id(s2))
# 注意两点:一 __new__方法中是否有else
# 二 线程安全的