创建单例模式
import threading
import time
class Singleton:
instance = None
# 加锁是为了当多线程调用时,防止出现多线程执行太快都去新建了一个对象,这就违背了单例模式的意义
lock = threading.RLock()
def __init__(self, name):
self.name = name
def __new__(cls, *args, **kwargs):
"""
提前再做一次判断是因为想要优化一下性能,当我们在1000行代码后
又想调用直接在这里判断不需要再继续往下申请锁再判断
"""
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():
obj = Singleton('x')
print(obj)
for i in range(10):
t = threading.Thread(target=task)
t.start()
# 1000行代码。。。
obj = Singleton('x')
print(obj)
标签:__,obj,模式,instance,单例,return,cls
From: https://www.cnblogs.com/piggthird/p/17879602.html