I am teaching a Python course and now reviewing my upcoming material on multi-threading. Last year, I used the following program to demonstrate to students that if two threads try to modify a global variable at the same time, then something messy is going to happen...
#!/usr/bin/env python3
"""Example of a simple race condition"""
import threading
MAX = 1_000_000
# global variable
counter: int = 0
def count() -> None:
"""Target function"""
global counter
for _ in range(MAX):
counter += 1
def main() -> None:
"""Main function"""
thread1 = threading.Thread(target=count)
thread2 = threading.Thread(target=count)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print(f"{counter = :_}")
if __name__ == '__main__':
main()
But I was astonished to discover that using Python version 3.10, there is no mess at all, and the counter gives the "correct" final value, no matter how many times I run the script, on Windows or Linux.
Python specialists, how can multiple threads update a global variable just fine in Python 3.10 ?