python 单例模式线程安全的示例

普通的单例是不安全,必须要在单例对象里面,加入线程锁,才能达到线程安全

import threading

def synchronized(func):
    func.__lock__ = threading.Lock()

    def synced_func(*args, **kws):
        with func.__lock__:
            return func(*args, **kws)

    return synced_func

def Singleton(cls):
    instances = {}

    @synchronized
    def get_instance(*args, **kw):
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]

    return get_instance

def worker():
    single_test = test()
    print("id----> %s" % id(single_test))


@Singleton
class test():
    a = 1

if __name__ == "__main__":
    task_list = []
    for one in range(5):
        t = threading.Thread(target=worker)
        task_list.append(t)

    for one in task_list:
        one.start()

    for one in task_list:
        one.join()

# 运行效果
id----> 2082136725432
id----> 2082136725432
id----> 2082136725432
id----> 2082136725432
id----> 2082136725432
原文地址:https://www.cnblogs.com/ygbh/p/13752894.html