Python Global Interpreter Lock
This tutorial will give us a piece of information about the Python Global Interpreter Lock (GIL).
What is Global Interpreter lock (GIL) in Python
Python global interpreter lock(GIL) is a process lock in Python. It is using in Python for restricting the multi-thread processing,
This is because all the statements can execute by using a single thread in Python.
And the performance of using a single thread and multiple threads is the same. so, Python provides the GIL for locking all the statements in a single thread.
Why we chose the GIL:
We choosing the GIL as a solution for locking the single thread for processing in Python,
This is because Python libraries are mostly written in the C and C++ and Python supports C language at the back end.
Because of the GIL Python provides the thread-safety.
Example 1: Global Interpreter Lock
import time from threading import Thread count=4000 def startcount(c): while c>0: c-= 1 s=time.time() startcount(count) end = time.time() print('Time taken in seconds -', end - s)
Output: Time taken in seconds - 0.001051187515258789
Example 2: GIL in Python
import multiprocessing import time count=4000 def startcount(c): while c>0: c-=1 s=time.time() pro1= multiprocessing.Process(target=startcount,args =(count//2, )) #process1 creation pro2= multiprocessing.Process(target=startcount,args =(count//2, )) #process2 creation pro1.start() #process1 start pro2.start()#process2 start pro1.join() #wait until process1 is complete pro2.join() #wait until process2 is complete end = time.time() print('Time taken in seconds -', end - s)
Output: Time taken in seconds - 0.11368775367736816
From the above two examples, We observe that the two programs giving the result as same, Even though example 1 consisting of one thread
and example 2 consisting of two threads.
So, because of this reason Python using only single thread processes and for that purpose Python using GIL for locking the single thread for executing only one thread at a time.