Python: GIL (Global Interpreter Lock)

Rahul S
2 min readSep 27, 2023

The Global Interpreter Lock is a mutex (short for mutual exclusion) that protects access to Python objects, preventing multiple threads from executing Python bytecodes in parallel. It is built deep into the Python system and it is not possible at the moment to get rid of it.

In simpler terms, it ensures that only one thread can execute Python code at a time, even on multi-core processors. This can have performance implications, especially in CPU-bound multi-threaded Python programs.

It makes threading not truly concurrent. It locks the interpreter, and even though it looks like we are working with threads, they are not executed at the same time, resulting in performance losses.

Here are some ways to work around the GIL in Python:

  1. **Use Multiprocessing**: One of the most common ways to bypass the GIL is to use the `multiprocessing` module instead of the `threading` module.

`multiprocessing` allows you to create multiple processes, each with its own Python interpreter and memory space, which can run concurrently. This enables true parallelism, as each process operates independently of the GIL.

2. **Use Native Extensions**: You can write CPU-bound code in languages like C or C++ and create Python extensions (using…

--

--