#直接上代码
import threading
import time
def single(cls):
instance = {}
lock = threading.Lock()
def __single(*args,**kwargs):
print("lock" + str(lock))
if cls not in instance:
with lock:
if cls not in instance:
instance[cls] = cls(*args,**kwargs)
return instance[cls]
return __single
@single
class x():
def __init__(self):
time.sleep(2)
def getCls():
print(x())
for i in range(20):
threading.Thread(target=getCls).start()
脚本运行结果如下:
本文通过一个Python示例,展示了如何在多线程环境中实现线程安全的单例模式。代码中使用了threading模块的Lock来确保在多线程环境下实例化的唯一性,避免了资源竞争的问题。
1069

被折叠的 条评论
为什么被折叠?



