我试着用下面的代码在Python语言中演示一个竞态条件,但总是得到期望值0。是不是我的代码出了什么问题,只是它不够“密集”,不足以触发竞态条件?谢谢。
import threading
import time
def race_cond():
foo = 0
flag = threading.Event()
def mutator():
flag.wait()
nonlocal foo
foo += 1
foo -= 1
foo += 1
ts = [threading.Thread(target=mutator)
for i in range(10000)]
[t.start() for t in ts]
flag.set()
[t.join() for t in ts]
return foo
for i in range(100):
print(f'Expecting 10000, actual: {race_cond()}')发布于 2018-06-18 22:50:52
mutator()不会改变任何东西;实际上,它会抛出一个错误,因为您正在尝试更改一个没有在该函数中定义的局部变量。为了更改foo,您需要在函数中使用global foo。
https://stackoverflow.com/questions/50912070
复制相似问题