fs = dict()
lock = Lock()
def singleflight(key, func):
with lock:
if key in fs:
wait = True
f = fs[key]
else:
wait = False
f = [None, Event()]
fs[key] = f
if wait:
f[1].wait()
r = f[0]
else:
r = func()
f[0] = r
f[1].set()
with lock:
fs.pop(key, None)
return r
【代码】缓存击穿保护器singleflight
最新推荐文章于 2025-08-21 23:46:05 发布
本文介绍了一种使用Python实现的单例模式,通过`Lock`对象确保线程安全。核心内容涉及了在多线程环境下如何避免重复创建并正确同步关键资源。
456

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



