Sub topic 12
Under the hood: reference counting, immortal objects and allocator changes
This chapter explains the main interpreter changes that let CPython run without the GIL. It assumes you know what the GIL protects, how to detect a free-threaded build, and the basics of data races and locks from earlier chapters. It also assumes you know that CPython frees most objects by counting references to them. You don't need C skills, but the chapter refers to the C structures behind every Python object.
Why the GIL made reference counting cheap
Every CPython object carries a reference count. Assigning an object to a name, putting it in a list, or passing it to a function raises the count. Removing the reference lowers it. When the count reaches zero, the interpreter frees the object immediately.
With the GIL, only one thread runs bytecode at a time, so count += 1 on that field needs no protection. It compiles to a plain increment. Remove the GIL and two threads can increment the same field at once. Both read 5 and both write 6. The count is now one too low. The object can be freed while something still points to it, which corrupts memory instead of merely giving a wrong answer.
Making every increment an atomic CPU instruction fixes correctness, but it is slow. Reference counts change constantly, and atomic operations on a shared cache line force cores to wait for each other. The free-threaded build therefore combines several techniques, covered below. They are biased reference counting, immortal objects, deferred reference counting, a new allocator, and per-object locks.
Biased reference counting
PEP 703 builds on a observation: most objects are only ever touched by the thread that created them. The free-threaded build splits the single count into two fields in the object header.
| Header field | Who updates it | How |
|---|---|---|
| Owner thread id | Set at creation | Records which thread owns the object |
| Local count | The owner thread only | Plain, non-atomic increments and decrements |
| Shared count | Every other thread | Atomic operations |
The owner thread pays almost no extra cost, because its updates are ordinary arithmetic on a field no one else writes. A different thread uses the slower atomic path on the shared field.
The object is freed only when the combined count reaches zero. When a non-owner thread drops the last shared reference, the runtime has to make sure the owner's local count is also zero before freeing. The details are subtle, because a negative shared count is legal and the owner can be asked to "merge" the two fields. You never see any of this from Python code. You only see that single-threaded code stays fairly fast.
Immortal objects
Some objects are used by every thread all the time: None, True, False, small integers, and interned strings such as attribute names. If every thread atomically updated the count on None, that one cache line would become a bottleneck for the whole program.
The fix is to make these objects immortal. An immortal object has a reserved count value that the increment and decrement code recognizes. Reference changes on it are skipped, so the object is never freed and its count is never written.
PEP 683 introduced immortal objects in Python 3.12 for a different reason: sharing memory between forked processes without triggering copy-on-write. The free-threaded build reuses the idea for scalability. In it, the local count field holds the maximum 32-bit value to mark an object as immortal.
You can observe this from Python:
import sys
a = []
before = sys.getrefcount(a)
b = a # one more reference to the same list
after = sys.getrefcount(a)
print("Extra references:", after - before)
# On Python 3.12 or later, None and small ints are immortal,
# so their reported count is a huge constant, not a real tally.
print("None immortal-looking:", sys.getrefcount(None) > 2**31)
print("Small int immortal-looking:", sys.getrefcount(5) > 2**31)On Python 3.12 or later, the first line prints 1 and the other two print True. The exact large number is an implementation detail, so don't compare against it. Test with > as above, or avoid depending on it.
Immortality has a cost. Immortal objects are never freed until the interpreter exits, so a program that creates many immortal objects keeps that memory. The set of immortal objects is therefore kept small. Interned strings are one of the largest groups, which is why interning behavior differs a little between builds.
Deferred reference counting
Immortality doesn't help objects that are shared by many threads but must eventually be freed, such as functions, code objects, modules and classes. Every call to a function would otherwise increment and decrement that function's count from many threads.
For these objects the free-threaded build uses deferred reference counting. References held on the interpreter's own evaluation stack are not counted at all. The object is instead freed only by the cyclic garbage collector, which can check that no stack references remain. This trades prompt freeing for lower contention. In Python 3.13 the build mostly made such objects immortal as a stopgap. Python 3.14 uses deferred counting for functions, code objects and similar objects, so the stopgap is smaller there.
The allocator: mimalloc replaces pymalloc
Standard CPython uses pymalloc, a fast allocator for small objects that is safe only because the GIL serializes access. It keeps global pools with no locking.
The free-threaded build replaces it with mimalloc, a general-purpose allocator designed for multi-threaded programs. Its key properties for this chapter are:
- Per-thread heaps. Each thread allocates from its own heap, so allocations rarely contend.
- Size classes and pages. Memory is split into pages that each hold objects of one size class.
- Cross-thread frees. A thread that frees an object another thread allocated puts it on a lock-free list for the owning heap to reclaim.
- Heap traversal. The allocator can walk all live objects of a given kind. The garbage collector relies on this.
That last point matters. The standard collector keeps linked lists of tracked objects, which needs extra header fields and locking. The free-threaded build instead finds objects by scanning mimalloc's pages, which removes those list pointers.
Garbage collection changes
The cyclic garbage collector also changes. In the Python 3.13 free-threaded build, collection is not generational: there is a single generation. It also stops the world. All threads pause at a safe point while the collector examines every object, and then they resume. Pauses can be longer for programs with very large object graphs, which is a trade-off to watch when you measure latency.
Per-object locks and other supporting changes
Reference counts are only one piece. Built-in containers also need protection now that the GIL is gone. The build adds a small mutex to each object header. Operations on a list, dict or set take that object's lock through a mechanism called a critical section, which is why a single list.append stays safe.
Critical sections also release the lock if the thread blocks, which prevents deadlocks between two containers. Separately, the free-threaded build in 3.13 turns off the specializing adaptive interpreter, because its in-place bytecode rewriting wasn't yet thread-safe. Python 3.14 re-enables it, which narrows the single-thread slowdown.
What this means in practice
- Single-thread speed. Biased counting, immortal objects and mimalloc keep the slowdown moderate. It is larger in 3.13 than in 3.14, partly because of the disabled specializing interpreter.
- Memory use. Per-thread heaps, the larger object header and immortal objects raise memory use compared with the standard build.
- Object lifetime. Deferred counting and the stop-the-world collector mean objects such as functions may be freed later than you expect. Don't rely on exact timing of
__del__for them. - C extensions. Extensions that touch
ob_refcntdirectly, or usepymallocassumptions, break. They must use the public macros and functions, which is part of why extensions need to be rebuilt for the free-threaded ABI.
Exercise
A free-threaded program has many threads calling the same module-level function in a hot loop. Name two techniques from this chapter that keep those calls from contending on one reference-count cache line, and say which kind of object each technique applies to.
Show answer
Immortal objects apply to objects that never need to be freed, such as None, True, False, small ints and interned strings. Their counts are never written, so threads don't contend on them. Deferred reference counting applies to shared objects that can still be freed, such as functions, code objects and modules. References on the evaluation stack aren't counted, and the cyclic garbage collector decides when the object can be freed. (Biased reference counting also helps for objects used mostly by their owner thread.)
Exercise
Why can't the free-threaded build keep using a plain, non-atomic count += 1 on a single reference-count field, and how does biased reference counting reduce the cost of the fix?
Show answer
Without the GIL, two threads can read the same count and both write back the same incremented value, losing an update. That can free an object that is still referenced. Making every update atomic is correct but slow. Biased reference counting gives each object an owner thread that updates a local count with ordinary arithmetic, while other threads use an atomic shared count. Most objects are touched mainly by their owner, so most updates stay cheap.