【发布时间】:2021-10-18 13:48:41
【问题描述】:
如果我使用布尔值来控制线程的循环,如果我在检查它的值之前没有锁定它,可能会发生什么。可以引发异常吗?
请注意,如果我的循环再次运行,这不是问题,但如果可能的话,我想避免锁定资源的成本
# self is the same object in the 2 functions
def __init__(self):
self.status=True
# thread 1
def stop(self):
# Lock acquired to avoid concurrent writes
self.lock.acquire()
self.status=False
self.lock.release()
# thread 2
def thread_func(self):
while self.status:
# Do stuff
# Not important if it does a cycle more after status is set to false
【问题讨论】:
-
这能回答你的问题吗? Is Python variable assignment atomic?
-
@mkrieger1 我需要对此进行一些澄清,因为该帖子的第二个答案。我这边的问题是阅读是否会导致异常。它是来自内存的简单加载,因此它不会发生吗?或者尝试加载正在写入的内存区域可以提高它?
标签: python python-3.x