Sub topic 8
Spotting data races and non-atomic operations
This chapter assumes you know the threading module, what a race condition is, and the basics of locks. It also assumes you have read the earlier chapters on the GIL and on built-in type thread safety.
What a data race is
A data race happens when two threads access the same piece of shared state at the same time, at least one of them writes, and nothing orders the accesses. The result then depends on timing, so it can change from run to run.
Under the GIL, many races stayed hidden. Only one thread ran bytecode at a time, and the interpreter switched threads only at certain points. Code that was technically unsafe often worked. On a free-threaded build, threads run on separate cores, and the same code can fail much more often.
Why `counter += 1` is not atomic
An operation is atomic if no other thread can observe it half done. The statement counter += 1 looks like one step, but it is three:
- Read the current value of
counter. - Add 1 to it.
- Store the result back in
counter.
If two threads both read 5, both compute 6, and both store 6, one increment is lost.
Reproducing the problem
This program has the same shape as the locked example in the next chapter, but without the lock.
import threading
counter = 0
def work(n):
global counter
for _ in range(n):
counter += 1
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(counter) # expected 400000On a free-threaded build, run it a few times. You will usually see a number below 400000, and the number will differ between runs. On a standard build the result is often correct, but that is luck, not a guarantee. The language never promised that counter += 1 is safe.
Common non-atomic patterns
Look for any sequence where the code reads shared state, decides something, and then writes. Typical cases:
| Pattern | Why it is unsafe |
|---|---|
| `x += 1`, `d[k] += 1` | Read, modify and write are separate steps. |
| `if k not in d: d[k] = v` | Another thread can insert `k` between the check and the write. |
| `if lst: lst.pop()` | The list can become empty after the check. |
| `x = x + [item]` on shared data | It reads, builds a new list, then rebinds. Concurrent updates are lost. |
| Lazy initialization of a global | Two threads can both see "not yet created" and both create it. |
This is the check-then-act pattern. Each individual operation may be safe, but the combination is not.
What built-in types still protect
Free-threaded CPython keeps individual operations on built-in types such as list.append and dict.__setitem__ safe. They will not crash the interpreter or corrupt the object's internal structure. This protects the container. It does not protect your logic. A sequence of two safe calls can still be a race.
import threading
cache = {}
def get_or_create(key):
if key not in cache: # check
cache[key] = object() # act: another thread may have run in between
return cache[key]Each dictionary operation here is safe. Two threads can still both pass the check and store different objects for the same key, so callers may receive different objects.
How to spot races in review
Ask these questions about each piece of state:
- Is it shared by more than one thread, such as a global, a class attribute, or an object passed to threads?
- Is it ever written after threads start?
- Does any code read it and then write based on what it read?
- Does anything depend on two variables staying consistent with each other?
If the answers are yes, the code needs a lock or a different design. The next chapter shows how to protect shared state with locks.
Exercise
A function does if name not in registry: registry[name] = load(name) on a shared dict, and runs on many threads. Each dict operation is individually safe. Why can this still be a bug, and what is the name of the pattern?
Show answer
It is a check-then-act race. Two threads can both find name missing, and both call load(name) and store a result. The work runs twice, and different callers may get different objects. The two steps need to run as one unit, for example under a lock.