I believe this is a difference in Python 3.10 and above from older versions. Could someone explain this?
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)
Why does this code does not produce a race condition in Python 3.11?
However, when I change this line to
counter += int(1)
then the race condition occurs.
Based on https://old.reddit.com/r/learnprogramming/comments/16mlz4h/race_condition_doesnt_happen_from_python_310/k198umz/:
In this case you can check the bytecode translation using dis and notice the
CALL_FUNCTIONbytecode instruction: