double-checked locking成语在某些语言中并不可靠,我想知道 Python 是否是其中之一。更具体地说,是下面的代码...
# Objects shared by threads:
obj = None
lock_for_obj = threading.Lock()
def get_obj():
"""Function called concurrently by threads."""
if obj is None:
with lock_for_obj:
if obj is None:
obj = factory() # Never returns `None`
return obj
...Python 中的线程安全?是否存在/不存在的场景/实现?为什么?
最佳答案
看看PEP 583 - Concurrency memory model for Python , 已撤回。
我想它被撤回的原因(虽然我找不到足够的信息)是因为有 different implementations of Python ,并且很难对每个人都执行这样的标准。
结论:当在单个处理器上使用 CPython 实现时,此代码可能是安全的,或者使用 Jython 实现时通常使用它可能是安全的,但不能保证。
关于python - 双重检查锁定在 Python 中是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55957708/