Race condition
A race condition is a bug whose result depends on the unpredictable timing of threads or tasks. Two interleavings that should be equivalent are not, so the program is sometimes wrong.
Detailed Explanation
Races are not "threads are hard" in the abstract. They are a missing atomicity. if key not in cache: cache[key] = load(key) can run load twice. balance -= 10 can drop an update. list.append in CPython happens to be atomic; list += [x] is not a single opcode sequence you should bet on for a larger invariant. Document the invariant ("at most one load per key") and protect the whole check-then-act.
The GIL makes some single bytecodes appear safe and teaches a false lesson. It does not make your compound operations safe. Free-threaded CPython makes that lesson urgent. Write locks or use queues as if the GIL were gone.
Asyncio races are real even on one thread. Two tasks can await between the check and the write. if not ready: ready = True; await start() can start twice. asyncio.Lock or a single task that owns the state is the fix. Single-threaded does not mean single-task.
Time-of-check to time-of-use (TOCTOU) is a race against the world: if path.exists(): path.unlink() can fail because another process deleted the file. Catch FileNotFoundError instead of pre-checking.
Fixes: a lock around the critical section; queue.Queue so only one thread mutates; concurrent.futures with no shared writes; dict.setdefault or capture patterns that are still not enough for "load once" without a lock; functools.cache is not thread-safe for the underlying dict in all versions — check if you share it.
Tests rarely catch races. Add a stress loop, or model the interleaving. If a test "fails on CI only", suspect a race before you suspect the OS.
Code Examples
import threading
# Race: both threads may pass the check and both increment from the same value.
count = 0
def bump() -> None:
global count
value = count
count = value + 1
# Fixed:
lock = threading.Lock()
def bump_safe() -> None:
global count
with lock:
count += 1# Async race: await between check and set.
ready = False
async def start_once(start, lock):
async with lock:
global ready
if not ready:
ready = True
await start() # still hold the lock only if start must be uniqueCommon Gotchas
"The GIL will serialise this"
compound statements are many bytecodes. Lock the invariant.
Check then act on the filesystem
another process can win the gap. Use exclusive create (`"x"`) or catch the error.
Tests that pass locally
increase scheduling noise (`time.sleep(0)` is not enough). Look at shared writes.
CPython atomicity of `append` is an implementation detail
do not build a protocol on it.