0

I was expecting a race condition to occur here. But it doesn't. Why?

import threading

x = 0

def foo():
    global x
    for i in range(1000):
        print x
        x += 1

def bar():
    global x
    for i in range(1000):
        print x
        x -= 1

if __name__ == "__main__":
    t1 = threading.Thread(target=foo)
    t2 = threading.Thread(target=bar)

    t1.start(); t2.start()
    t1.join(); t2.join()

    print x

The final value of x always 0. Not only that it seems that the second thread only starts to run after thread 1 has completed it's execution.

martineau
  • 119,623
  • 25
  • 170
  • 301
SouvikMaji
  • 1,088
  • 3
  • 22
  • 39
  • 1
    Python GIL global interpreter lock. – Jean-François Fabre Mar 20 '17 at 09:47
  • In simple words , only one thread is active at a time . In Python , multi threading does not mean concurrent execution . Its just quick context changes . – Abhimanyu singh Mar 20 '17 at 10:30
  • Re, "it seems that the second thread only starts to run after thread 1 has completed." I don't know how much of a time slice Python gives to one runnable thread before switching to the next, but it does not take long for a modern computer to count to 1000. – Solomon Slow Mar 20 '17 at 14:15

0 Answers0