#直接上代码
import threading
import time
def single(cls):
instance = {}
lock = threading.Lock()
def __single(*args,**kwargs):
print("lock" + str(lock))
if cls not in instance:
with lock:
if cls not in instance:
instance[cls] = cls(*args,**kwargs)
return instance[cls]
return __single
@single
class x():
def __init__(self):
time.sleep(2)
def getCls():
print(x())
for i in range(20):
threading.Thread(target=getCls).start()
脚本运行结果如下: