0

In a tutorial on threading.Lock, it gives an example of two threads writing the same global variable without any lock. The tutorial doesn't specify which version of Python it uses.

import threading


num = 0


def add():
    global num
    for i in range(1000000):
        num += 1


def desc():
    global num
    for i in range(1000000):
        num -= 1


def main():
    t1 = threading.Thread(target=add)
    t2 = threading.Thread(target=desc)
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    print(num)


main()

Run the code multiple times and the results are expected to be random each time, demonstrating that it goes wrong without a lock in this case. If it's run by Python2.7, the results are indeed different. However, with Python3.x (I use Python3.10), the results are always 0.

As t1 and t2 are joined, the main thread is blocked until add and desc are finished. To my understanding, num += 1 and num -= 1 are atomic operations. I think, no matter how the two threads run, both num += 1 and num -= 1 are executed for 1000000 times before print(num), so num should always be 0 at last. And I don't think it's necessary to use a Lock instance in this case. However, according to the results in Python2.7, it's not true.

We have a lot of scripts that run in either Python2.7 or Python3.x, so I'd like to figure it out why it behaves differently. Thanks for any help.

blhsing
  • 91,368
  • 6
  • 71
  • 106
ElpieKay
  • 27,194
  • 6
  • 32
  • 53

0 Answers0