我相信这是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)
然后出现竞争条件。
代码工作正常,我尝试了两个版本都返回了一些结果
投票