Sub topic 8
Spotting data races and non-atomic operations
This chapter assumes you know how to start threads with threading or concurrent.futures, and that you know what a race condition and a lock are. You should also be comfortable reading short Python bytecode listings. Chapter 7 covered what built-in types guarantee under free-threading. This chapter shows where those guarantees stop and your own code becomes the problem.
Two kinds of race
A data race happens when two threads access the same memory location at the same time, and at least one of them writes. A race condition is broader. The result of your program depends on how the threads' steps interleave.
In free-threaded CPython, the interpreter protects its own internals. Individual operations on built-in objects, such as list.append or dict.__setitem__, take a per-object lock internally, so they will not corrupt the object or crash the interpreter. What the interpreter cannot protect is a sequence of operations that your logic treats as one step. Those sequences are called non-atomic. An atomic operation is one that no other thread can observe half-finished.
So the bugs in this chapter are logic bugs. The interpreter stays intact, but your data can be wrong.
Why `counter += 1` is not atomic
One line of Python often becomes several bytecode instructions. You can see this with the dis module.
import dis
counter = 0
def bump():
global counter
counter += 1
dis.dis(bump)The exact opcodes differ between versions. On every version, the listing contains the same four steps:
- Load the current value of
counter. - Load the constant
1. - Add the two values.
- Store the result back into
counter.
If two threads both perform step 1 before either performs step 4, both compute the same new value. One increment is lost. This is a lost update.
The GIL could also switch threads between these steps, so this bug exists in standard CPython. In practice, switches are rare enough that many programs seemed to work. Without the GIL, threads really do run at the same moment, and the same code starts losing updates quickly.
Observing a lost update
This program starts four threads at the same moment and compares the final count with the expected count.
import sys
import threading
counter = 0
N = 200_000
THREADS = 4
def work(barrier):
global counter
barrier.wait() # start all threads together
for _ in range(N):
counter += 1
barrier = threading.Barrier(THREADS)
threads = [threading.Thread(target=work, args=(barrier,)) for _ in range(THREADS)]
for t in threads:
t.start()
for t in threads:
t.join()
gil = sys._is_gil_enabled() if hasattr(sys, "_is_gil_enabled") else True
print(f"GIL enabled: {gil}")
print(f"Expected {N * THREADS}, got {counter}")Run it on a free-threaded build with PYTHON_GIL=0. The result is usually lower than 800000, and it differs on each run. On a standard build, you may see the exact total many times in a row. A correct result on one run proves nothing, because races are timing-dependent.
Check-then-act
Another common pattern is to test a condition and then act on it. Another thread can change the condition between the two steps.
import threading
import time
cache = {}
created = []
def get(key):
if key not in cache: # check
time.sleep(0.001) # widens the window for the demo
created.append(key)
cache[key] = object() # act
return cache[key]
threads = [threading.Thread(target=get, args=("a",)) for _ in range(8)]
for t in threads:
t.start()
for t in threads:
t.join()
print("Objects created for key 'a':", len(created))Each of key not in cache, created.append, and cache[key] = ... is safe on its own. Together they are not. Several threads pass the check before any of them stores a value, so the "create once" rule breaks. The sleep only makes the window large enough to see reliably. Without it, the window is still there, only smaller.
The same shape appears in many forms:
if lst: lst.pop()can raiseIndexError, because another thread may empty the list after the check.if os.path.exists(p): open(p)can fail, because the file may vanish after the check.- Lazy initialization of a module-level global (
if _conn is None: _conn = connect()) can runconnect()more than once.
A reference table
Use this table as a first guide when you read code. "Atomic" means safe against interleaving on that one operation.
| Code | Atomic? | Reason |
|---|---|---|
| `x = value` (rebinding a name) | Yes | One store |
| `lst.append(v)`, `lst.pop()` | Yes | One locked method call |
| `d[k] = v`, `v = d[k]` | Yes | One locked operation |
| `n += 1` | No | Load, add, store |
| `d[k] += 1` | No | Read, add, then write |
| `lst[i] = lst[i] + 1` | No | Separate read and write |
| `if k not in d: d[k] = v` | No | Check-then-act |
| `d.setdefault(k, v)` | Yes for the dict | `v` is built before the call, so it may be wasted |
| `a, b = b, a` on shared names | No | Several loads and stores |
| `for x in lst: ...` while another thread mutates `lst` | No | May skip or repeat items |
"Atomic" here describes the operation on the object. It does not promise that your program is correct. For example, v = d[k] is atomic, but k may already have been deleted by the time you run it.
Broken invariants across several objects
Races are not limited to counters. Any rule that spans more than one variable can be broken halfway through an update.
import threading
class Account:
def __init__(self, balance):
self.balance = balance
def transfer(src, dst, amount):
src.balance -= amount # not atomic
dst.balance += amount # not atomic
a, b = Account(1000), Account(1000)
barrier = threading.Barrier(2)
def run(src, dst):
barrier.wait()
for _ in range(100_000):
transfer(src, dst, 1)
t1 = threading.Thread(target=run, args=(a, b))
t2 = threading.Thread(target=run, args=(b, a))
t1.start(); t2.start()
t1.join(); t2.join()
print("Total:", a.balance + b.balance, "(should be 2000)")There are two problems. Each -= and += can lose updates. Also, any thread reading both balances between the two lines sees money missing. The second problem exists even if each single update were atomic. Fixing it needs the whole transfer protected as one unit.
Iterating while another thread mutates
Iterating over a container that another thread changes gives unreliable results.
- A
dictorsetcan raiseRuntimeError: ... changed size during iteration. - A
listiterator does not raise an error. It may skip items or visit some twice, because it tracks a numeric index.
To read a consistent view, take a snapshot, for example for x in list(shared):. The list(...) call copies the contents in one operation. Note that this is a snapshot, so it can be stale by the time you use it.
Finding races in practice
Races rarely show up in a single run. These habits help find them:
- Look for compound operations on shared state. Search for
+=,-=, andif ... not inon anything reachable from more than one thread. - Stress it. Use many threads, many iterations, and a
threading.Barrierso they start together. Run the test many times, not once. - Compare modes. Run the same test with
PYTHON_GIL=1andPYTHON_GIL=0on a free-threaded build. A test that passes with the GIL and fails without it points to code that was relying on the GIL's rare switches. - Use a thread sanitizer. CPython can be built with ThreadSanitizer support. It reports unsynchronized access at the C level. It is most useful for extension authors and interpreter developers.
- Check invariants. Assert totals and counts at the end of a stress test, as in the examples above, rather than only checking for crashes.
The fix, in brief
Every example above is fixed in the same way. Make the whole compound step run under one lock, or avoid sharing mutable state at all. For the counter, that looks like this:
import threading
counter = 0
lock = threading.Lock()
def work(n):
global counter
for _ in range(n):
with lock:
counter += 1The next chapter covers locks in detail, including lock scope, deadlocks, and other primitives. The chapter after it covers designs that avoid sharing in the first place.
Exercise
A worker thread runs stats[name] = stats.get(name, 0) + 1, and several workers run it on the same shared dict at the same time. Each call (get, +, and __setitem__) is safe on its own. Is the line safe? If not, say what goes wrong and name one fix.
Show answer
It is not safe. Two threads can both read the same old value with get, both add one, and both store the same result, so one increment is lost. The line is a read-modify-write sequence, even though each call is safe individually. A fix is to run the whole line inside with lock: using a shared threading.Lock. Another fix is to give each worker its own dict and merge the results after the threads are joined.
Exercise
Why does a stress test that passes 100 times on a standard build not show that the code is thread-safe? Name one way to make the test stronger.
Show answer
Under the GIL, thread switches happen only at specific points and fairly rarely, so many races stay hidden. A passing run only shows that the bad interleaving did not occur. To strengthen the test, use more threads and iterations, start the threads together with a barrier, assert an invariant (such as the final total) at the end, and run it on a free-threaded build with PYTHON_GIL=0, where threads truly run at the same time.