Sub topic 1
What the GIL is and why CPython has one
Prerequisites
This chapter assumes you know the following:
- Basic Python syntax and functions.
- The
threadingmodule orconcurrent.futures, at the level of starting a thread and joining it. - The difference between a process and a thread: processes have separate memory, threads share it.
- What a race condition is and what a lock does.
You do not need to know C or CPython internals. Where the chapter touches them, it explains the idea first.
What the GIL is
The Global Interpreter Lock (GIL) is a mutex inside the CPython interpreter. A mutex is a lock that only one thread can hold at a time. A thread must hold the GIL to execute Python bytecode, which is the low-level instruction set the interpreter runs. If you have ten Python threads, at most one of them runs bytecode at any instant.
Three points are easy to get wrong:
- The GIL belongs to the CPython interpreter, not to the Python language. Other implementations make different choices. Jython and IronPython have no GIL.
- Each interpreter has its own GIL. Threads in one process share it. Separate processes each have their own interpreter, so they do not compete for it.
- The GIL does not make your programs thread-safe. It makes the interpreter's internals safe. Your own multi-step updates can still be interrupted. Later chapters return to this.
You can still write threaded programs in standard CPython. The threads are real operating system threads, scheduled by the OS. The GIL decides which of them may run Python code.
How a thread gets and gives up the GIL
A thread gives up the GIL in two situations.
- It is about to block. Calls such as
time.sleep(), socket reads, file reads, and waiting on a lock release the GIL while they wait. Another thread can run Python code in the meantime. - It has held the GIL too long. If other threads are waiting, the interpreter asks the running thread to yield after a time slice, called the switch interval. The default is 5 milliseconds.
You can inspect and change the switch interval:
import sys
print(sys.getswitchinterval()) # 0.005 by default
sys.setswitchinterval(0.001)
print(sys.getswitchinterval())The switch happens between bytecode instructions, not in the middle of one. That detail matters for the next section and for the chapter on data races.
Why CPython has a GIL
The GIL is a design decision from the early 1990s, when CPython was first written. It solves one main problem and gives several side benefits.
Reference counting
CPython manages memory mostly with reference counting. Every object has a counter of how many references point to it. Assigning an object to a name increments the counter. Dropping a reference decrements it. When the counter reaches zero, the object is freed immediately.
You can see the counter with sys.getrefcount:
import sys
data = []
print(sys.getrefcount(data)) # 2: the name `data` plus the temporary argument
other = data
print(sys.getrefcount(data)) # 3
del other
print(sys.getrefcount(data)) # 2Incrementing and decrementing the counter is a read-modify-write sequence in C: read the count, add one, write it back. If two threads do this on the same object at once without protection, one update can be lost. A lost increment leads to a counter that is too low. The object may be freed while something still points to it, which crashes the interpreter or corrupts memory. A lost decrement leaks memory.
Reference counts are touched on almost every operation, so protecting each one is expensive. Per-object locks would need a lock for every object, plus rules to avoid deadlocks. One global lock is much simpler.
What the single lock buys
With the GIL, the whole interpreter can assume that only one thread is manipulating Python objects at a time. This gives CPython:
- Safe reference counts with plain, non-atomic increments. Non-atomic operations are cheap.
- Simple, fast single-threaded code. There is no locking overhead on every object access.
- Safe built-in types. Operations such as
list.appendanddict.__setitem__run to completion without another thread seeing a half-updated structure. - Easy C extensions. Extension authors can call into the C API and assume the interpreter state is not changing underneath them. This made it easy to wrap existing C libraries, which is a large part of why NumPy and similar projects exist in Python.
The last point had a lasting effect. A huge body of extension code relies on the GIL for correctness, and that is why removing the GIL is hard, as a later chapter explains.
What the GIL protects, and what it does not
It helps to separate three layers.
| Layer | Protected by the GIL? | Example |
|---|---|---|
| Interpreter internals | Yes | Reference counts, memory allocator state, the frame stack |
| Individual built-in operations | Mostly yes | A single `list.append(x)` call |
| Your multi-step logic | No | `counter += 1`, check-then-act on a dict |
The second row is "mostly" because the guarantee comes from the fact that a C-implemented operation does not release the GIL part way through. It is an implementation detail rather than a documented promise for every operation. Operations that call back into Python code, such as __eq__ or __hash__ methods on keys, can switch threads in the middle.
The third row is where the common mistake lies. Consider this statement:
counter += 1It looks like one step, but the interpreter compiles it to several bytecode instructions. You can see them with dis:
import dis
def increment():
global counter
counter += 1
dis.dis(increment)The output shows a load of the global, a load of the constant, an in-place add, and a store back to the global. The exact opcode names vary between Python versions. The important part is that a thread switch can occur between the load and the store. Two threads can both load the value 5, both compute 6, and both store 6. One increment is lost.
The GIL makes this less likely, because switches only happen at specific points. It does not make it impossible. Code that appears to work under the GIL can contain such bugs and pass every test for years. This matters later: removing the GIL does not create these bugs, but it exposes them far more often.
What the GIL does to performance
The GIL has different effects depending on what the threads do.
- I/O-bound work (network calls, disk reads, waiting on a database). Threads spend most of their time blocked, and blocking releases the GIL. Threads give a real speedup here.
- CPU-bound work in pure Python (loops, arithmetic, parsing). Threads need the GIL to run, so they take turns. Four threads do not run four times faster. They often run slower than one thread because of the cost of switching.
- CPU-bound work in C code that releases the GIL. Some extensions, including parts of NumPy,
hashlib, andzlib, release the GIL during long computations. Threads can run in parallel inside those calls.
Here is a small experiment. It runs the same work on one thread and on four threads and prints the elapsed time:
import time
from concurrent.futures import ThreadPoolExecutor
def burn(n):
total = 0
for i in range(n):
total += i * i
return total
N = 5_000_000
if __name__ == "__main__":
start = time.perf_counter()
for _ in range(4):
burn(N)
serial = time.perf_counter() - start
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=4) as pool:
list(pool.map(burn, [N] * 4))
threaded = time.perf_counter() - start
print(f"serial: {serial:.2f}s")
print(f"threaded: {threaded:.2f}s")On a standard CPython build, the two times are about the same, and the threaded one is sometimes a little slower. The exact numbers depend on your machine. On a free-threaded build, the threaded version can approach a fourfold speedup if you have at least four free cores. The next chapters cover that.
The usual workarounds
Because of the GIL, Python developers have used several strategies for CPU-bound parallelism.
multiprocessingorProcessPoolExecutor. Each worker is a separate process with its own interpreter and its own GIL. This gives real parallelism. The cost is memory, start-up time, and the need to pass data between processes by serializing it withpickle.- Native extensions that release the GIL. NumPy, Cython code with
nogil, and Rust or C libraries do heavy work outside the interpreter. - Asynchronous I/O (
asyncio). This does not give parallelism. It handles many I/O waits efficiently on one thread. - Subinterpreters. Since Python 3.12, each subinterpreter can have its own GIL. This is a different route to parallelism and is not the topic of this tutorial.
Free-threaded Python adds another option: ordinary threads sharing memory, with no GIL serializing them. The rest of the tutorial covers how that works and what you must do differently.
Common errors in the working model
- Believing threads are useless in Python. They are useful for I/O-bound work and for C code that releases the GIL.
- Believing the GIL makes all code thread-safe. It makes single built-in operations mostly safe. Compound operations are not.
- Believing the GIL is part of the language. It is a CPython implementation detail. The language reference does not require it.
- Expecting more threads to speed up CPU-bound pure Python. On a standard build they will not.
- Raising the switch interval to "fix" a race. This changes how often the bug shows up, not whether it exists.
Summary
The GIL is a single lock that lets only one thread run Python bytecode at a time. CPython has it because reference counting needs protection, and one global lock is the cheapest and simplest way to provide it. It also makes built-in types behave well under threads and makes C extensions easy to write. The price is that pure-Python CPU-bound threads cannot run in parallel. The next chapter looks at that limit in more detail and measures it.
Exercise
Two threads each run counter += 1 100,000 times on a shared global, with no lock, on a standard CPython build. Why can the final value still be less than 200,000, even though the GIL exists?
Show answer
The GIL ensures only one thread runs bytecode at a time, but it can switch threads between bytecode instructions. counter += 1 compiles to several instructions (load, add, store). If a switch happens after one thread loads the value and before it stores the result, the other thread's update is overwritten, so one increment is lost. The GIL protects the interpreter's internal state, not multi-step operations in your own code.
Exercise
A program downloads 200 web pages using four threads in standard CPython, and it is faster than a single-threaded version. A second program computes prime numbers in pure Python using four threads and is no faster than one thread. Explain both results.
Show answer
Downloading is I/O-bound. A thread waiting on the network releases the GIL, so other threads can run Python code or start their own requests, and the waits overlap. Prime counting is CPU-bound pure Python. Every thread needs the GIL to execute bytecode, so they take turns and the total work done per second does not increase.
Exercise
Why did CPython's designers choose one global lock instead of a lock on each object?
Show answer
Reference counts change on almost every operation, so per-object locking would add cost to every access, slow single-threaded programs, and require rules to avoid deadlocks. One global lock keeps reference counting cheap with plain increments, keeps built-in types safe, and makes C extensions simple to write.