Skip to content

GIL

I recently learned about Pythonโ€™s Global Interpreter Lock (GIL), which really deepened my understanding of concurrency in Python. I wanted to write a short post summarizing what I learned so I can return here occasionally and review what GIL is.


First, GIL is not a standardized feature of Python itself, but a property of widely used Python implementations such as CPython. Since CPython is the most commonly used implementation, programmers often assume the presence of GIL when writing Python code.

So, what is GIL?

GIL stands for the Global Interpreter Lock. As its name suggests, it is a global lock that allows only one thread to execute Python bytecode at any given time. This means there is no true parallelism between Python threads.

GIL does not automatically eliminate race conditions because it operates at the bytecode level. Conceptually, a line of Python code like counter += 1 can be compiled into multiple bytecode instructions:

LOAD counter
LOAD 1
ADD
STORE counter

A thread switch may occur somewhere in the middle, causing two threads to load the same value of counter and later write back the same result.

However, it is common for Python to call functions implemented in C. The thread that calls a C function generally holds on to the GIL until the function returns. This applies to built-in operations such as len(), list.append(), and dict.get(). One advantage of GIL is that these functions can be implemented without additional concurrency checks, since only one thread can execute them at a time.

Furthermore, GIL does not prevent a C function from spawning additional threads and parallelizing its work. Compute-intensive libraries such as NumPy may parallelize operations internally using native threads.

Limited parallelism between Python threads can hurt performance for compute-bound tasks, but GIL works fine in most other cases. It has little impact on sequential code and works well for I/O-bound tasks, where a thread can release GIL while waiting for I/O.

Before I end, I want to mention one part that I found slightly confusing. Python threads are native OS threads, but OS thread scheduling and the GIL operate at different levels. The OS decides which native thread runs, while the Python runtime controls which thread holds the GIL.

A thread holding the GIL may be suspended by the OS, but this does not automatically release the GIL. Other Python threads cannot execute Python bytecode until the thread holding the GIL releases it.


This post is a bit shorter than my other posts, but Iโ€™m not going to dive deeper into why CPython adopted GIL or whether it will be modified or removed in the future. Hopefully, I can return to this topic later and provide a more complete explanation. In the meantime, I think I now have a good understanding of GIL and multithreading in Python.