python 单例

参考博客:https://zhuanlan.zhihu.com/p/212234792

from threading import Thread, RLock

def Singleton(cls):
    instance = {}
    single_lock = RLock()

    def _singleton_wrapper(*args, **kargs):
        with single_lock:
            if cls not in instance:
                instance[cls] = cls(*args, **kargs)
        return instance[cls]

    return _singleton_wrapper

@Singleton
class Sun:
    def __init__(self, name):
        self.name = name
        print("sun init")

    def show_name(self):
        print(self.name)

def make_sun(n):
    sun = Sun(str(n))
    sun.show_name()



if __name__ == '__main__':
    n = 10
    threads = []
    for i in range(n):
        t = Thread(target=make_sun, args=(i,))
        threads.append(t)

    for i in range(n):
        threads[i].start()

    for i in range(n):
        threads[i].join()
文章目录