Python Can';我的代码是否按顺序运行?

Python Can';我的代码是否按顺序运行?,python,multithreading,python-3.x,race-condition,Python,Multithreading,Python 3.x,Race Condition,我试图用下面的代码演示Python中的竞争条件,但总是得到期望值0。我的代码有什么问题吗?只是不够“密集”,不足以触发比赛条件?多谢各位 import threading import time def race_cond(): foo = 0 flag = threading.Event() def mutator(): flag.wait() nonlocal foo foo += 1 foo -=

我试图用下面的代码演示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()}')

mutator();事实上,它会抛出一个错误,因为您试图更改一个未在该函数中定义的局部变量。为了更改
foo
您需要在函数中使用
global foo

也意味着您可能不会看到此代码的竞争条件。查看
dis.dis(mutator)
foo
的修改肯定不是原子的,所以在理论上应该有一个竞争条件,GIL是字节码级别的一次执行限制。上述代码仍可能被执行,从而导致竞争条件@TomDaltonYep公平点谢谢你指出这一点。我刚刚更正了代码,但仍然没有打印出意外值。