Python 装饰器线程安全单例的实现

#直接上代码

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()
    

脚本运行结果如下:Python 装饰器线程安全单例的实现_第1张图片

你可能感兴趣的:(python,多线程)