python_interview_question icon indicating copy to clipboard operation
python_interview_question copied to clipboard

一般面试的话写单例最好写出线程安全的模式

Open tcc0lin opened this issue 4 years ago • 1 comments

import threading
class Singleton(object):
    _instance_lock = threading.Lock() 
     
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
          with Singleton._instance_lock:
            if not hasattr(cls, '_instance'):
                cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
        return cls._instance
    
    
class Foo(Singleton):
    pass

foo1 = Foo()
foo2 = Foo()

print(foo1 is foo2)  # True

tcc0lin avatar Mar 13 '20 09:03 tcc0lin