python3.8 和 python3.11 之间意外的线程不安全行为

问题描述 投票:0回答:0

我玩弄了一些线程不安全的 Python 代码:

# main.py

from threading import Thread

count = 0


def update_count(value):
    global count
    for _ in range(2_000_000):
        count += value


def main():
    global count
    for i in range(20):
        print(f'Start run #{i + 1}')
        count = 0
        pos = Thread(target=update_count, args=[100])
        neg = Thread(target=update_count, args=[-100])
        pos.start()
        neg.start()

        pos.join()
        neg.join()

        if count != 0:
            print(f'Thread unsafe, count={count}')


main()

但是,如果我使用

python3.11
运行上面的代码,则不会遇到线程不安全的情况。 同时,如果我用
python3.8
运行代码,它会返回线程不安全的结果,例如:
Thread unsafe, count=91222600
.

你能帮我理解为什么会这样吗?

更新 1:我可以在我的 Mac 和 Windows PC 机器上重现这个。 更新 2:我还在其他版本的 python 上进行了测试。 Python 从 3.7 到 3.9 运行示例返回线程不安全,而 Python 3.10 和 3.11 似乎运行示例线程安全。

python thread-safety
© www.soinside.com 2019 - 2024. All rights reserved.