Sub topic 12
Under the hood: reference counting, immortal objects and allocator changes
This chapter assumes you know what the GIL protects, how to detect a free-threaded build, and why counter += 1 is a data race. It explains the interpreter changes that let threads run bytecode in parallel. You don't need this to write thread-safe code, but it explains the performance numbers and some surprising behavior.
Why reference counting is the problem
CPython frees an object when its reference count drops to zero. Every assignment, function call, and list append changes a count. In the standard build, the GIL makes ob_refcnt += 1 safe because only one thread runs bytecode at a time.
Without the GIL, two threads can read the same count, both add one, and write back the same value. The count is now too low. The object may be freed while still in use, which crashes the interpreter. Putting an atomic operation or lock on every count change would slow everything down, so PEP 703 changes the design instead.
Biased reference counting
The free-threaded build splits the count into two fields:
- A local count, updated with plain, non-atomic operations. Only the thread that owns the object touches it.
- A shared count, updated with atomic operations. Any other thread uses it.
Most objects are used mostly by the thread that created them, so most updates take the cheap path. The count is "biased" toward the owner. When a different thread takes a reference, it pays for an atomic update. An object is freed when both counts show that nothing refers to it.
Immortal objects
Some objects live as long as the interpreter does: None, True, False, small integers, and interned strings. Updating their counts from many threads would cause constant contention on the same memory. In the free-threaded build these objects are immortal. Their count is never changed, so reading and passing them around involves no writes at all.
Standard CPython 3.12 and later also has immortal objects (PEP 683), mainly to support sharing objects between subinterpreters. In the free-threaded build the same idea also removes contention.
import sys
# Immortal objects report a very large, fixed count.
print(sys.getrefcount(None))
a = None
print(sys.getrefcount(None)) # unchanged after taking another referenceThe exact number depends on the build and version. What matters is that it does not change.
Deferred reference counting
Some objects, such as functions, modules, and code objects, are referenced by many threads at once. Counting each reference would again cause contention. The free-threaded build can use deferred reference counting for these. References from the interpreter's own stack are not counted, and the garbage collector works out whether the object is still alive.
Allocator changes
The standard build uses pymalloc, a fast allocator that relies on the GIL for its safety. The free-threaded build replaces it with mimalloc, a thread-aware allocator that keeps separate heaps per thread. It also tracks object types in a way that lets the garbage collector find every object.
The garbage collector changes too. It is no longer generational. It runs as a stop-the-world collector, which pauses all threads briefly while it examines objects.
Per-object locks
Built-in containers need protection without a global lock. Each list, dict, and set has its own small lock, taken inside operations such as append or item assignment. This is why a single list.append is safe in a free-threaded build. It does not make a sequence of operations safe. A check followed by an insert is still two steps.
Summary of the changes
| Area | Standard build | Free-threaded build |
|---|---|---|
| Reference counts | Plain increment under the GIL | Biased: local and shared counts |
| Long-lived objects | Mostly counted (immortal since 3.12) | Immortal, or deferred counting |
| Allocator | pymalloc | mimalloc |
| Garbage collector | Generational | Stop-the-world, non-generational |
| Container safety | The GIL | Per-object locks |
Exercise
Why does the free-threaded build keep a separate local and shared reference count instead of making every count update atomic?
Show answer
Atomic updates are slower than plain ones. Most objects are used mostly by the thread that created them, so the owner updates a plain local count cheaply. Only other threads pay for an atomic update of the shared count.
Exercise
A colleague says "list.append is safe in free-threaded Python, so my check-then-append code is safe too." What is wrong with that claim?
Show answer
Each list operation takes the list's own lock, so a single append is safe. A check followed by an append is two separate operations, and another thread can change the list between them. You still need a lock around the whole sequence.