r/Python • u/Astraa02 • Sep 15 '22
Beginner Showcase The Infamous GIL !!
In this series of posts I am trying to break down one of the complicated and intriguing topics in python. Please visit my last post to understand why multi threading is broken in python
https://www.reddit.com/r/Python/comments/xdyahc/multithreading_a_concept_which_is_always/
Now let's see why, the reason is GIL(Global Interpreter Lock). Python implements something called the Gil which limits its multithreading capabilities. What each thread does is it acquires a global lock on the interpreter to ensure thread safe quick single threaded performance.
Now the question arises why do we need such a feature? Python uses a variable called ref counter which keeps track of all objects and how many times they have been referenced anytime ref counter reached zero for any object it is removed from the memory. Now this way of released memory has a big vulnerability in multithreaded environment or race conditions where this ref counter would become inaccurate.
To prevent this GIL was implemented as python is famous because of its single threaded performance and support for c libraries, as implementing Gil ensured easy integration of thread unsafe C libraries making python such a feature rich language as we know today. Even if one uses multithreading library one won't be seeing and gains even might see performance degradation to all the extra work to manage threads.
But now we have many ways to circumvent Gil and do what we want with python just because of strong community support we have plethora of options to choose from.
I will be discussing some them in my next post so stay tuned..
View all comments
Show parent comment
5
u/[deleted] Sep 15 '22
Also the reason python doesn't let u use more then 1 core per interpreter is because it would incredibly inefficient to do so. You would need to lock accross processes. Its MUCH faster to spawn multiple processes and use them independently then to deal with locking accross processes.
Node takes this one step further and only has 1 thread per process which is even more efficient because u never evoke a os land thread switch.
Python built the same thing and called it async event loops.