gsb22
gsb22

Reputation: 2180

Why python GIL is not kicking in for this multithreaded code?

I run the following piece of pure python code and in my understanding GIL should kick in and avoid simultaneous access to variable x and hence x should have sum for first 10 million numbers but it doesn't work and gives different result every-time which makes me believe that there in no mutex when both threads are accessing variable x.

from threading import Thread

x = 0


def task_1():
    global x
    for i in range(5000000):
        x += i


def task_2():
    global x
    for i in range(5000001, 10000000):
        x += i


t1 = Thread(target=task_1)
t2 = Thread(target=task_2)

t1.start()
t2.start()

t1.join()
t2.join()

print(f"X value is {x}")

Upvotes: 2

Views: 127

Answers (1)

sheldonzy
sheldonzy

Reputation: 5961

x += y is not an atomic operation. You can read more under What kinds of global value mutation are thread-safe?

Also, remember that multithreads in Python are not for CPU bound programs (like yours). The GIL here only means that only one thread will run at the same time, regardless of how many cores there are.

And note that your code is trying to sum the first 10 million numbers minus 5,000,000 since you skipped it in task_2, and it is not included in task_1.

Upvotes: 3

Related Questions