python Python中实现的单例,双重判断

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Python中实现的单例,双重判断相关的知识,希望对你有一定的参考价值。

#encoding=utf8
import threading

class Singleton(object):
    """
    ***Python实现单例模式(类似Tronado.IOLoop)***
    关键点:**双重判断,二层加锁**,各种语言实现方式都类似
    """
    _instance_lock = threading.Lock()

    @staticmethod
    def instance():
        if not hasattr(Singleton, '_instance'):
            with Singleton._instance_lock:
                if not hasattr(Singleton, '_instance'):
                    Singleton._instance = Singleton()
        return Singleton._instance

以上是关于python Python中实现的单例,双重判断的主要内容,如果未能解决你的问题,请参考以下文章