Sub topic 7
What built-in types guarantee under free-threading
This chapter assumes you know basic Python, have used threading or concurrent.futures, and understand what a race condition is. Earlier chapters covered the GIL and how to run a free-threaded build. This one asks a narrower question. When several threads run truly in parallel, what can you still rely on from list, dict, set, and int?
The short answer
On a free-threaded build, the interpreter protects its own data structures. A list, dict, or set shared by many threads will not crash the interpreter or corrupt its internal memory. Each single operation on these objects completes as a unit.
Your program's logic gets no such protection. Anything made of several steps, such as "read, change, write back", can be interleaved with other threads. That was already true under the GIL, but the GIL hid many of those bugs. Free-threading exposes them.
Two different kinds of safety
Keep these two ideas apart. Most confusion about free-threading comes from mixing them up.
| Kind of safety | Meaning | Who provides it |
|---|---|---|
| Memory safety | The interpreter never crashes or corrupts its own structures | The interpreter, through internal locks and atomic reference counting |
| Logical correctness | Your program computes the right answer | You, through locks and good design |
Memory safety is what the "built-in types guarantee". Logical correctness is still your job.
How built-in containers stay consistent
Under the GIL, one global lock made every bytecode instruction exclusive. Free-threaded CPython removes that lock. Mutable built-in containers instead use a small lock attached to each object. A method such as list.append takes that object's lock, changes the structure, and releases the lock. Two threads appending to the same list take turns. Two threads appending to different lists do not block each other.
Some reads avoid the lock entirely. For example, indexing a list or looking up a dict key can often proceed without locking, using techniques that detect concurrent changes and retry. As a user you do not see this. It explains why free-threaded builds can scale read-heavy workloads well.
Single operations that are safe to share
The following are individual operations on built-in objects. In the current implementation each one completes as a unit, so no other thread sees a half-finished result:
lst.append(x),lst.pop(), andlst[i] = xd[key] = value,d.get(key), andkey in ds.add(x)ands.discard(x)d.setdefault(key, default)when the keys are built-in types such asstrorint
The key-type condition on setdefault matters. Hashing and comparing a key can run Python code if the key's class defines __hash__ or __eq__. That code can run while the container is being examined, so the operation may no longer be a single unit. Keys of built-in types such as str, int, and tuple of those avoid the problem.
The next example shows a safe single operation. Many threads append to one shared list, and no appended items are lost.
import threading
results = []
def work(start):
for i in range(start, start + 10_000):
results.append(i)
threads = [threading.Thread(target=work, args=(n * 10_000,)) for n in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print(len(results)) # 40000Every append lands, and the list stays well formed. The order of items from different threads is not predictable, though. Only the total is.
Compound operations are not atomic
Many lines that look like one step are several steps. counter += 1 means "read the value, add one, store the result". Two threads can both read the same old value, and one update is then lost.
The same applies to containers. d[key] += 1 is a read of d[key], an addition, and a write to d[key]. Each individual step is safe, but the combination is not.
import threading
counts = {"hits": 0}
def work(n):
for _ in range(n):
counts["hits"] += 1 # read, add, write: three steps
threads = [threading.Thread(target=work, args=(100_000,)) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print(counts["hits"]) # often less than 400000 on a free-threaded buildThe dictionary is never corrupted, but the printed total is often too small. On a free-threaded build this loss is easy to reproduce. Under the GIL it was rare and timing dependent, which is why such bugs shipped unnoticed.
Check-then-act
Another common pattern is checking a condition and then acting on it:
cache = {}
def get_value(key, compute):
if key not in cache: # check
cache[key] = compute(key) # act
return cache[key]Two threads can both see the key missing. Both compute the value, and the second write overwrites the first. If compute has side effects or is expensive, that is a bug. If the function must return one consistent object per key, two threads may even return different objects. A lock around the whole check-and-act sequence fixes it. The next chapters cover locks in detail, but here is the minimal version:
import threading
cache = {}
cache_lock = threading.Lock()
def get_value(key, compute):
with cache_lock:
if key not in cache:
cache[key] = compute(key)
return cache[key]This is correct but holds the lock while compute runs, so other threads wait. For slow computations you may prefer a design that tolerates duplicate work, such as computing outside the lock and then using cache.setdefault(key, value) to keep the first stored result.
Iteration while another thread modifies the container
Looping over a list, dict, or set while another thread changes it does not crash the interpreter. The loop can, however, skip items, see an item twice, or raise RuntimeError: dictionary changed size during iteration. Under the GIL you could get the same effects, but free-threading makes them far more likely.
Two safe approaches:
- Take a snapshot under a lock, then iterate over the snapshot:
with lock: items = list(d.items()). - Do the whole iteration inside the lock, if it is short.
Iterator objects themselves, such as the result of iter(lst), are also not designed to be shared between threads. Giving the same iterator to several threads can produce duplicated or skipped values. Give each thread its own iterator, or hand out items through a queue.Queue.
Immutable objects and reference counts
Immutable built-in objects such as int, str, tuple, and frozenset cannot change after creation, so reading them from many threads is always safe. Rebinding a name is a different matter. total = total + 1 creates a new int and stores it, and that read-then-store sequence can still race.
Python tracks how many references point to each object, and that count is updated by many threads at once. The free-threaded build makes these updates safe with techniques covered in the internals chapter. For now, note that you do not need to protect reference counts yourself, and a shared object will never be freed while a thread still holds a reference to it.
A practical checklist
- Treat one call to one method on a built-in container as safe, but keep that as a convenience and not a design basis.
- Treat any sequence of two or more operations on shared state as unsafe until you protect it with a lock.
- Do not iterate over a container that other threads may modify, unless you hold a lock or work on a copy.
- Do not share one iterator between threads.
- Prefer designs that avoid shared mutable state, which later chapters cover.
Exercise
A free-threaded program has stats = {"errors": 0} shared by eight threads. Each thread runs stats["errors"] += 1 in a loop. The dictionary never raises an error, yet the final count is lower than expected. Explain why, and show a fix.
Show answer
stats["errors"] += 1 is three steps: read the value, add one, write it back. Each step is safe on its own because the dict's internal lock protects its structure, but another thread can run between the read and the write. Two threads then read the same old value and one increment is lost. The fix is to make the whole update one protected unit: create lock = threading.Lock() and write with lock: stats["errors"] += 1.
Exercise
Which of these is a single operation on a built-in object, and which needs a lock if the object is shared? (a) items.append(7) (b) if name not in seen: seen.add(name); process(name)
Show answer
(a) is a single operation, and the list's internal lock keeps it consistent. (b) needs a lock, because the check and the add are separate steps. Two threads can both find name missing and both call process(name). Wrap the check, add, and decision in one with lock: block, and call process after the block if it is slow and the decision has already been made.