Sub topic 5
What the GIL is and what it protects
This chapter assumes you can start threads with threading, you know what a race condition is, and you have seen why counter += 1 needs a lock. It builds on the earlier chapters on threads and locks. It does not cover how the GIL affects speed. The next chapter covers that.
The GIL in one paragraph
The Global Interpreter Lock (GIL) is a mutex inside CPython, the standard Python implementation. A thread must hold it to execute Python bytecode. Only one thread in a process holds it at any moment, so only one thread runs Python code at a time, even on a machine with many cores. The lock belongs to the interpreter, not to your program. You never acquire it yourself.
Two points are easy to get wrong:
- The GIL is a feature of CPython, not of the Python language. Other implementations, and the free-threaded builds of CPython described at the end of this chapter, work differently.
- The GIL does not make your code thread-safe. It protects the interpreter's own data. It does not protect your data.
Why CPython has it
CPython manages memory with reference counting. Every object carries a counter of how many references point to it. Assigning a name to an object increments the counter. Deleting or rebinding the name decrements it. When the counter reaches zero, the memory is freed immediately.
Suppose two threads update the same counter at the same moment without synchronization. Both can read the value 5 and both write back 6. The true count is now wrong. If the count ends up too low, the object is freed while something still uses it, and the process crashes. If it ends up too high, the object is never freed, and memory leaks.
CPython has two broad ways to prevent this:
- Put a lock on every object, or on every reference-count update. This is fine-grained locking. It costs time on every operation, and it makes single-threaded code slower.
- Put one lock around the whole interpreter. Reference counts, the memory allocator, and the built-in containers are then safe by construction, and single-threaded code pays almost nothing.
CPython chose the second option. It also made writing C extensions easier, because extension authors could assume that their code was not interrupted by other Python threads while it held the GIL.
What the GIL protects
The GIL protects the interpreter's internal state:
- Reference counts on all objects.
- The object allocator and other internal bookkeeping.
- The internal structure of built-in types. A
list.appendordict.__setitem__call cannot corrupt the list or dict in the middle of the operation.
Because of this, you cannot crash CPython or corrupt a dict just by touching it from two threads. A threaded Python program can still compute wrong answers, but it will not fail with a memory fault in pure Python code.
What the GIL does not protect
The GIL is held per bytecode instruction, not per line of Python. The interpreter can switch threads between instructions. Any operation that takes several instructions can be interrupted in the middle.
You can see this with the dis module:
import dis
counter = 0
def increment():
global counter
counter += 1
dis.dis(increment)On CPython 3.13 the output includes these instructions, with exact names and extra lines varying by version:
LOAD_GLOBAL counterreads the current value.LOAD_CONST 1pushes the number 1.BINARY_OP (+=)computes the sum.STORE_GLOBAL counterwrites the result back.
Another thread can run between the load and the store. If it does, one of the two increments is lost. This is the same race you protected with a lock in the previous chapter. The GIL did not prevent it.
| Question | Protected by the GIL? |
|---|---|
| Can two threads corrupt a list's internal memory? | Yes, this cannot happen |
| Can `counter += 1` lose an update? | No, you need a lock |
| Can a check-then-act sequence such as `if key not in d: d[key] = ...` run twice? | No, you need a lock |
| Is each individual `list.append` call safe? | Yes, in current CPython |
| Does it order operations across several objects? | No |
Single operations that look atomic
Some single operations, such as list.append(x), dict[key] = value and queue.Queue.put, are effectively atomic under the GIL, because each one completes inside a single C function. People often generalize from this and write code that depends on it.
Do not depend on it. It is an implementation detail, not a language guarantee, and the free-threaded builds use per-object locks to keep it working, at some cost. If a sequence of operations must be consistent, hold a threading.Lock. If you need to pass items between threads, use queue.Queue.
How threads take turns
A thread does not hold the GIL until it finishes. Two mechanisms release it.
Forced switching on a timer
A thread that runs Python code continuously is asked to give up the GIL after a fixed interval. A waiting thread sets a flag. The running thread notices the flag at a safe point between bytecode instructions, releases the GIL, and one of the waiting threads takes it.
You can read the interval:
import sys
print(sys.getswitchinterval()) # 0.005 by default, in secondsThe default is 5 milliseconds. You can change it with sys.setswitchinterval, but you should rarely need to. A shorter interval makes threads switch more often and adds overhead. A longer interval reduces switching but makes other threads wait longer for their turn.
Voluntary release when blocking
A thread releases the GIL when it calls into code that waits, such as time.sleep, socket reads, file reads, and Lock.acquire. While it waits, other Python threads run. When the call returns, the thread must reacquire the GIL before it continues running Python code.
This is the reason threads help with I/O-bound work. The next chapter develops it.
Checking whether the GIL is on
Since Python 3.13 you can ask the interpreter whether the GIL is enabled. Earlier versions always have one.
import sys
# sys._is_gil_enabled() exists in Python 3.13 and later; older versions always have a GIL.
gil_enabled = getattr(sys, "_is_gil_enabled", lambda: True)()
print("GIL enabled:", gil_enabled)The function name starts with an underscore, so treat it as a diagnostic, not as a stable API for production logic.
Gotchas and failure modes
- Assuming the GIL makes code thread-safe. The usual symptom is a result that is wrong only some of the time. A race may not appear in a short test, because the switch interval is long compared with a few instructions. A program that passes a hundred runs can still contain the bug. Lock shared state anyway.
- Assuming more threads make CPU-bound code faster. Only one thread runs Python bytecode at a time. Extra threads add switching and lock contention, so a CPU-bound job can run slower with threads than without them.
- Holding the GIL in a long C call. A C extension that does not release the GIL blocks every other Python thread for the duration of the call. One slow extension call can freeze a thread-based server. A later chapter covers libraries that release the GIL.
- Blaming the GIL for everything. Slow threaded code is often caused by lock contention in your own code, by blocking calls that were not as asynchronous as expected, or by too much work per task. Measure first.
- Thinking processes share the GIL. Each process has its own interpreter and its own GIL. That is why separate processes can use several cores. The cost is that they do not share memory directly.
GIL versus other locks
The GIL is not the same as a threading.Lock:
- The GIL is held automatically, by the interpreter, around all bytecode execution. A
Lockis held only where you writewith lock:. - A
Lockprotects a specific section of code that you choose. The GIL protects the interpreter's internals, and it is released at arbitrary points between bytecode instructions. - You can hold a
Lockacross a blocking call. The GIL is released during that call.
Because the GIL can switch away at almost any instruction, you should reason about thread safety as if the GIL did not exist. Then your code remains correct on builds without it.
Where this is heading
Python 3.13 introduced an optional free-threaded build, in which the GIL can be disabled. It is experimental, and its details may change between releases. The final chapter of this tutorial covers it. For now, the practical rule is to write code that is correct without relying on the GIL, and to use the GIL only to explain why CPU-bound threads do not scale on a standard build.
Exercise
Two threads each run total += 1 on a shared global variable 100,000 times, with no lock. Because CPython has a GIL, can the final value still be less than 200,000? Explain which part of the interpreter the GIL protects and which part it does not.
Show answer
Yes. The GIL protects the interpreter's internal state, such as reference counts and the internal structure of built-in objects. It does not make a multi-instruction operation atomic. total += 1 compiles to separate load, add, and store instructions, and a thread switch can happen between them, so one thread can overwrite the other's update. A threading.Lock around the increment fixes it.
Exercise
A thread calls time.sleep(2). What happens to the GIL during the sleep, and why does that matter for programs that wait on the network?
Show answer
The thread releases the GIL while it sleeps, and reacquires it when the call returns and it needs to run Python code again. Other Python threads can run during the wait. Network calls release the GIL in the same way, so threads that mostly wait can overlap their waiting even though only one thread runs bytecode at a time.