I play around with some thread-unsafe Python code:
# 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()
However, if I run the code above with python3.11
, there is no thread-unsafe encounter.
Meanwhile, if I run the code with python3.8
, it will return thread-unsafe results, for example: Thread unsafe, count=91222600
.
Can you help me understand why it is happening?
Update 1: I can reproduce this on both my Mac & Window PC machines. Update 2: I also test on other versions of python. Python from 3.7 to 3.9 runs the example return thread-unsafe, while Python 3.10 & 3.11 seems to run the example thread-safe.