多线程数据安全的单例模式
import threading
class Singleton:
instance = None
lock = threading.RLock()
def __init__(self):pass
def __new__(cls, *args, **kwargs):
if cls.instance:
return cls.instance
with cls.lock:
if cls.instance:
return cls.instance
cls.instance = object.__new__(cls)
return cls.instance
def task():
single = Singleton()
print(single)
for i in range(5):
t = threading.Thread()
t.start()