# 创建型模式-单例模式(使用装饰器实现)
# 线程锁:防止创建多个实例
# 双重检查:实例创建后,防止重复加锁占用资源
from threading import Lock
from concurrent.futures import ThreadPoolExecutor
def single_decorator(cls):
_lock = Lock()
_instince = {}
def wrapper(*args, **kwargs):
if cls not in _instince:
with _lock:
if cls not in _instince:
import time
time.sleep(1)
_instince[cls] = cls(*args, **kwargs)
return _instince[cls]
return wrapper
@single_decorator
class Test():
pass
def get_instance():
b = Test()
print(id(b))
if __name__ == "__main__":
poll = ThreadPoolExecutor(max_workers=5)
for i in range(10):
poll.submit(get_instance)