Sub topic 7
What built-in types guarantee under free-threading
This chapter assumes you know the threading module, what a race condition is, and the difference between a single operation and a sequence of operations. It also assumes you have read the earlier chapters on the free-threaded build.
Internal safety versus logical safety
Without the GIL, two threads can run inside the same list or dict at once. CPython's built-in containers handle this by taking a short per-object lock inside each method call. The docs call this a critical section.
This gives you one guarantee. A single built-in operation on a single object, such as list.append or dict.__setitem__, runs as one step. The object's internal state is never corrupted, and the interpreter does not crash.
It does not give you logical safety. Your program is still responsible for any code that uses several operations together.
Single operations stay safe
This program appends from four threads. It prints the correct total on a free-threaded build and on a standard build:
import threading
items = []
def work(n):
for i in range(n):
items.append(i)
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(len(items)) # 400000No append is lost, because each append takes the list's lock for its duration.
Compound operations are not atomic
Each line below looks like one step, but it is several:
| Code | What actually happens |
|---|---|
| `counter += 1` | read, add, write back |
| `d[k] += 1` | `d[k]` lookup, add, `d[k]` store |
| `if k not in d: d[k] = v` | membership test, then a separate store |
| `x = lst[-1]; lst.pop()` | two separate calls |
Another thread can run between any two steps. Each step is safe by itself, but the sequence is not.
import threading
counts = {"hits": 0}
def work(n):
for _ in range(n):
counts["hits"] += 1 # lookup, add, store: updates can be lost
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 under free-threadingThe dictionary is never damaged. The count is simply wrong, because two threads can read the same old value and both write back the same new one.
Safe uses of single calls
Some methods do a whole check-and-act in one call, so they are safe where the manual version is not:
d.setdefault(k, v)instead ofif k not in d: d[k] = v.lst.pop()on a list that may be empty, wrapped intry/except IndexError, instead of checkingif lst:first.queue.Queue.putandget, which are built for this and covered in a later chapter.
When a sequence must be atomic and no single method does it, use a lock. The next chapter covers that.
Iteration while another thread mutates
Iterating over a list or dict while another thread changes it will not crash the interpreter. You may still see odd results:
- A
dictiterator raisesRuntimeErrorif the size changes during iteration. - A
listiterator may skip or repeat elements if items are inserted or removed.
To iterate safely, either hold a lock around the loop or iterate over a snapshot such as list(d.items()). Taking the snapshot is a single call and is atomic with respect to that container. The loop over the copy is then private to your thread.
Limits of the guarantee
- User-defined methods. If a key's
__hash__or__eq__is written in Python, that code runs during the dictionary operation. The built-in lock may be released while it runs, so the operation is not guaranteed atomic. - Other types. The guarantee covers the built-in containers. Objects from third-party or user code have only the safety they implement themselves.
- Not a language promise. Treat the atomicity of single built-in operations as an implementation property of CPython, not a rule of the language. Use locks for anything your correctness depends on.
Exercise
A teammate writes if name not in registry: registry[name] = create() where registry is a shared dict. Why can this fail on a free-threaded build even though dict operations are thread-safe, and what is a minimal fix?
Show answer
The membership test and the store are two separate operations. Two threads can both see that the name is missing, and both call create() and store a value, so one result is overwritten and duplicate work happens. A minimal fix is to hold a threading.Lock around the whole check-and-store sequence. registry.setdefault(name, create()) is atomic, but it always calls create() first, so use the lock if create() is expensive or has side effects.