liveBook · Manning

Reference counting

As explained in Python Concurrency with asyncio

A memory-management technique that tracks the number of active references to each object and reclaims an object when that count reaches zero.

Reference counting manages memory by tracking how many active references point to each object. It increments when a reference is added, decrements when one is removed, and deletes the object when the count reaches zero. section 1.5

In CPython, reference counting helps explain the global interpreter lock: simultaneous reference-count updates could produce an incorrect count, so the operation must be protected from competing threads. section 1.5

A simultaneous update

If two threads increment the same reference count at once, both may read the same old value and write back the same incremented value. The expected count of two becomes one, creating a race condition. section 1.5

Figure 1.6 A race condition where two threads try to increment a reference count simultaneously. Instead of an expected count of two, we get one.
01-06

Visualizes two threads attempting to increment one reference count simultaneously and losing one update. section 1.5

How Python Concurrency with asyncio covers it

How deep it goes
Defines incrementing, decrementing, reclamation, and a lost-update race, without detailing broader garbage-collection internals.
Examples
Uses integers, dictionaries, lists, and a two-thread reference-count increment race to make the mechanism concrete.
What you can do after
Evaluate how reference-count updates contribute to CPython's thread-safety constraints and the global interpreter lock.
How it connects
Connects memory management with CPython, the global interpreter lock, threads, multiprocessing, shared variables, and race conditions.

Also explained in

Compare how 4 books explain reference counting →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.