使用python写一个线程安全的单例

单例在各类编程语言开发中都很常见,前面咱们使用Java OC swift 分别对单例进行了探讨,下面咱们使用python写一个线程安全的单例。python

import threading


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

    def lock_func(*args, **kwargs):
        with func.__lock__:
            return func(*args, **kwargs)

    return lock_func


class Singleton(object):
    instance = None

    @synchronized
    def __new__(cls, *args, **kwargs):
        """ :type kwargs: object """
        if cls.instance is None:
            cls.instance = super().__new__(cls)
        return cls.instance


if __name__ == "__main__":
    a = Singleton(3)
    print("a单例! id为 %s" % id(a))
    b = Singleton(4)
    print("b单例! id为 %s" % id(b))
    str = "hello world !"
    c = Singleton(str)
    print("c单例! id为 %s" % id(c))
    
    print("ok!")
复制代码

在python3中,调用父类的方法是用super()来调用。 咱们这里经过锁来进行保护,保证多线程的状况下同一时刻只有一个线程访问,这就保证了单例模式的安全 将类传入单例修饰器中,若是该类还未生成实例(instances中不存在该类),那么就生成一个新的实例返回,并记录在instances中。若是已经instances中已经存在该类,那么直接返回实例cls.instance编程

id是内置方法,咱们经过id来判断对象是不是单例。运行结果以下swift

python线程安全的单例
相关文章
相关标签/搜索