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

2019-04-18  本文已影响0人  CoderZS

单例在各种编程语言开发中都很常见,前面我们使用Java OC swift 分别对单例进行了探讨,下面我们使用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来判断对象是否是单例。运行结果如下

python线程安全的单例
上一篇 下一篇

猜你喜欢

热点阅读