加锁
但是使用类方式创建的单例,无法支持多线程,因此使用加锁的方式;
未加锁部分并发执行,加锁部分串行执行,速度降低,但是保证了数据安全
import threading
class Singleton(object):
_instance_lock = threading.Lock()
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
with Singleton._instance_lock:
if not hasattr(Singleton, "_instance"):
Singleton._instance = object.__new__(cls)
return Singleton._instance