多线程下,使用new实现单例
import threading
class Test(object):
from threading import Lock
lock = Lock()
flag = None
def __new__(cls, *args, **kwargs):
with cls.lock:
if cls.flag is None:
cls.flag = super().__new__(cls)
return cls.flag
def func():
res = Test()
print(res)
t = threading.Thread(target=func).start()
t2 = threading.Thread(target=func).start()
#<__main__.Msg object at 0x00000193A9C3A198>
#<__main__.Msg object at 0x00000193A9C3A198>