100 increments happen very fast, and means each thread will probably complete before the main thread has even started the next one. Bump that up to 1_000_000 or so and you'll probably trigger it.
I did a test with a print(x) at the start of test() to see what the number was when each thread kicked off, and the very first thread had got it up to 655,562 by the time the second thread had started and gotten to that print statement. -----Original Message----- From: Python-list <python-list-bounces+david.raymond=tomtom....@python.org> On Behalf Of ast Sent: Wednesday, December 4, 2019 10:18 AM To: python-list@python.org Subject: threading Hi An operation like x+=1 on a global variable x is not thread safe because there can be a thread switch between reading and writing to x. The correct way is to use a lock lock = threading.Lock with lock: x+=1 I tried to write a program without the lock which should fail. Here it is: import threading x = 0 def test(): global x for i in range(100): x+=1 threadings = [] for i in range(100): t = threading.Thread(target=test) threadings.append(t) t.start() for t in threadings: t.join() print(x) 10000 The result is always correct: 10000 Why ? Secondly, how the switch between threads is done by the processor ? Is there a hardware interrupt coming from a timer ? -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list