import threading
x = 0;
class Thread1(threading.Thread):
def run(self):
global x
for i in range(1,100000):
x = x + 1
class Thread2(threading.Thread):
def run(self):
global x
for i in range(1,100000):
x = x - 1
#create two threads
t1 = Thread1()
t2 = Thread2()
#start the threads
t1.start()
t2.start()
#wait for the threads to finish
t1.join()
t2.join()
print x;
Running this multiple times produces different output, some in the negative and some in the positive. Is it because the two threads are using the same global x? I don’t understand why: shouldn’t the net effect (output) be the same after all the dust settles?
Not necessarily. Imagine the following sequence of events. We’ll begin at a precise moment after the program has been running for a bit; both
Thread1andThread2are inside theirforloops, andx = 0Thread1has control. It accessesxto determine the value ofx + 1;xis0, so the result is1. However…Thread1completes the assignment, control passes toThread2.xis still0.Thread2now accessesx. It calculatesx - 1, which is-1, becausexis still0. Because of the unpredictability of thread timing, it manages to complete the operation, assigning-1tox.Thread1. It has already calculated the value ofx + 1to be1. It assigns1tox.Both threads have completed an iteration, and the value of
xshould be0, but its actual value is1.