Middle
What is GIL in Python and why does it not work with multithreading for CPU-bound tasks?
sobes.tech AI
Answer from AI
GIL (Global Interpreter Lock) is a mechanism in CPython that ensures only one thread executes Python bytecode at a time. This is done to simplify memory management and prevent issues with concurrent access.
Due to the GIL, multithreading in Python is inefficient for CPU-bound tasks, as threads cannot truly run in parallel on multiple processor cores — they take turns acquiring the GIL. In such cases, it's better to use multiprocessing (the multiprocessing module) or write critical sections in C/C++ with GIL release.
Example: if you have several threads, each calculating the factorial of a large number, they will work sequentially because of the GIL, not in parallel.