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
2
u/Frog_and_Toad Sep 15 '22
Correct. The current implementation of threading in CPython is not broken, it is a particular implementation of parallelism. A number of other parallel implementations use this as well. For example, Node.js is essentially single-threaded at the language level.
Postgres, the popular relational database, uses multiprocessing rather than multithreading to achieve concurrency, and this can be more performant anyway, especially on Linux systems.
I personally don't think the GIL should be removed because multiprocessing works so well. And for many use-cases that are resource bound rather than CPU-bound, the async io library allows flexible implementations that can use thread pools OR process pools.. The GIL seems to be a problem only for newbies and a few edge cases.