无法在 Python 3.11 中使用多线程创建竞争条件

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

我相信这是Python 3.10及以上版本与旧版本的区别。有人能解释一下吗?

import threading
import time

counter = 0

lock = threading.Lock()


def increment():
    global counter

    for _ in range(10**6):
        counter += 1


threads = []
for i in range(4):
    x = threading.Thread(target=increment)
    threads.append(x)

for t in threads:
    t.start()

for t in threads:
    t.join()

print(counter)

为什么这段代码在 Python 3.11 中不会产生竞争条件?

但是,当我将这一行更改为

counter += int(1)

然后出现竞争条件。

python python-3.x multithreading python-multithreading
1个回答
0
投票

代码工作正常,我尝试了两个版本都返回了一些结果

投票

© www.soinside.com 2019 - 2024. All rights reserved.