threading
ast
ast at invalid
Wed Dec 4 10:18:04 EST 2019
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 ?
More information about the Python-list
mailing list