# 创建型模式-单例模式(使用元类实现)
# 线程锁:防止创建多个实例
# 双重检查:实例创建后,防止重复加锁占用资源
# __call__作用:__call__方法使一个类的实例像方法一样调用,当我们调用一个实例时,实际就是调用了它的__call__方法
import time
from threading import Lock
from concurrent.futures import ThreadPoolExecutor
class Singletion(type):
_lock = Lock()
_instance = None
def __call__(cls, *args, **kwargs):
if not cls._instance:
with cls._lock:
if not cls._instance:
time.sleep(1)
cls._instance = super(Singletion, cls).__call__(*args, **kwargs)
return cls._instance
class Test(metaclass=Singletion):
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)