Member-only story
The Python Global Interpreter Lock or GIL, in simple words, is a mutex (or a lock) that allows only one thread to hold the control of the Python interpreter. This means that at any given time, only one thread can be in the state of execution.
If you only develop single-threaded Python programs, you might not feel the impact. But if you are doing multi-threading Python programming, GIL can become a bottleneck.
Let’t take a look at one example, the following is a very simple cpu-bound code:
def count_down(n):
while n > 0:
n -= 1
Now, assuming a large number n = 100000000
, let’s try executing count_down(n)
in a single thread.
My test environment has 2 CPUs, and the execution time is:
At this time, let’s try to use multi-threading to speed up, such as the following lines:
from threading import Thread
def count_down(n):
while n > 0:
n -= 1if __name__ == '__main__':
n = 100000000
t1 = Thread(target=CountDown, args=[n // 2])
t2 = Thread(target=CountDown, args=[n // 2])
t1.start()
t2.start()
t1.join()
t2.join()
Execute the above program again, the result this time looks like: