import time
import threading
class Singleton:
_lock = threading.Lock()
def __new__(cls, *args, **kwargs):
if not hasattr(Singleton, '_instance'):
with cls._lock:
if not hasattr(Singleton, '_instance'):
print('new successfully')
time.sleep(1)
Singleton._instance = super().__new__(cls)
return Singleton._instance
def __init__(self):
print("init....")
def init_singleton():
s = Singleton()
print(id(s))
if __name__ == '__main__':
for i in range(3):
t = threading.Thread(target=init_singleton)
t.start()
"""
new successfully
init....init....init....
2472451133888
2472451133888
2472451133888
"""
线程安全的单例模式