Race conditions
suggest changeA race condition is a bug where the result of a program depends on the timing of things running at the same time: threads, asyncio tasks, processes, or even other programs touching the same files. The code works when one thing runs at a time, and breaks only when two of them interleave in an unlucky order. That makes races hard to reproduce, and easy to miss in tests.
Almost every race follows one of two patterns:
- read-modify-write: read a value, compute a new one, write it back. Another thread writes in between and its update is lost.
- check-then-act: check a condition (
if key not in cache,if balance >= amount,if not os.path.exists(path)), then act on it. The condition is no longer true by the time you act.
The fix is always the same idea: make the whole sequence a single atomic step, either with a lock, with an operation that is atomic by design, or by not sharing the data at all.
This article shows what races look like in threads, asyncio, multiprocessing and the file system, and how to fix each one. Locks and synchronization covers the locking primitives themselves in detail.
All examples were run with Python 3.13.
Lost updates
Here four threads deposit money into one account. deposit() reads self.balance, calls a helper, and writes the new balance:
import threading
class Account:
def __init__(self):
self.balance = 0
def deposit(self, amount):
# read self.balance, call a method, then write self.balance
self.balance = self.balance + self.after_fees(amount)
def after_fees(self, amount):
return amount
account = Account()
def depositor(times):
for _ in range(times):
account.deposit(1)
threads = [threading.Thread(target=depositor, args=(500_000,)) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print("expected:", 4 * 500_000)
print("actual: ", account.balance)
expected: 2000000
actual: 1928121
The number is different on every run. The Global Interpreter Lock (GIL) lets only one thread run Python code at a time, but the interpreter can switch threads between bytecodes, for example when calling after_fees(). A typical bad interleaving:
- Thread A reads
balance= 100. - The interpreter switches to thread B, which reads
balance= 100 and writes 101. - Thread A resumes and writes 100 + 1 = 101.
Two deposits happened, but the balance only went up by one. Thread B's update is lost.
The fix is a lock around the read-modify-write, so no other thread can run the same sequence in the middle of it:
import threading
class Account:
def __init__(self):
self.balance = 0
self._lock = threading.Lock()
def deposit(self, amount):
with self._lock:
self.balance = self.balance + self.after_fees(amount)
def after_fees(self, amount):
return amount
account = Account()
def depositor(times):
for _ in range(times):
account.deposit(1)
threads = [threading.Thread(target=depositor, args=(500_000,)) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print("expected:", 4 * 500_000)
print("actual: ", account.balance)
expected: 2000000
actual: 2000000
Keeping the lock inside the class means callers can't forget to take it. Every method that reads or writes balance must use the same lock; a lock only protects code that actually acquires it.
counter += 1 is not atomic
+= looks like one operation, but it compiles to separate load, add and store steps:
import dis
counter = 0
def inc():
global counter
counter += 1
dis.dis(inc)
5 RESUME 0
7 LOAD_GLOBAL 0 (counter)
LOAD_CONST 1 (1)
BINARY_OP 13 (+=)
STORE_GLOBAL 0 (counter)
RETURN_CONST 0 (None)
A thread switch between LOAD_GLOBAL and STORE_GLOBAL loses an update, exactly like in the Account example. Yet a plain counter += 1 loop often gives the correct result:
import sys
import threading
counter = 0
def work(n):
global counter
for _ in range(n):
counter += 1
def run():
global counter
counter = 0
threads = [threading.Thread(target=work, args=(1_000_000,)) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
return counter
print("default switch interval:", sys.getswitchinterval())
print("result:", run())
sys.setswitchinterval(1e-6) # ask for thread switches as often as possible
print("result:", run())
default switch interval: 0.005
result: 4000000
result: 4000000
This is the worst kind of race: the bug is there, but it hides. In recent CPython versions the GIL is only handed over at certain points (function calls, loop back-edges), which happen not to fall inside this tiny loop body. Add a function call to the expression, run on a different Python version, or use the free-threaded build of Python 3.13+ (python3.13t) where threads truly run in parallel, and the same code loses updates. Never rely on the GIL for correctness: if more than one thread writes to a variable, protect it.
What is atomic and what isn't
In CPython, a single operation on a built-in type is thread-safe: other threads never see a half-finished list.append() or a corrupt dict. The free-threaded build keeps this guarantee by giving built-in objects their own internal locks. A sequence of operations is never atomic.
| Safe on its own | Not atomic |
|---|---|
lst.append(x), lst.pop() |
x += 1, obj.count += 1 |
d[k] = v, d.get(k), d.pop(k, None) |
d[k] += 1, d[k] = d.get(k, 0) + 1 |
d.setdefault(k, []) |
if k not in d: d[k] = [] |
deque.append(x), deque.popleft() |
if lst: lst.pop() |
queue.Queue.put() / get() |
iterating over a dict or list while another thread changes it |
A few patterns follow from this table:
- Use
d.setdefault(k, []).append(x)instead of "check, then insert, then append": the get-or-create is one call. - Use
queue.Queueorcollections.dequeto hand items between threads instead of a list with checks around it. - Anything that needs more than one step needs a lock, even if each step is safe by itself.
"Thread-safe" here means the object isn't corrupted. It doesn't mean your program's logic is correct: two safe calls in a row can still race with each other.
Iterating while another thread modifies
Iterating over a dict while another thread adds or removes keys is a race too. Python detects it and raises RuntimeError, but only when the bad interleaving actually happens:
import threading
import time
sessions = {}
stop = threading.Event()
def churn():
# simulates users logging in and out
i = 0
while not stop.is_set():
sessions[f"user{i}"] = time.time()
if len(sessions) > 1000:
sessions.pop(next(iter(sessions)))
i += 1
writer = threading.Thread(target=churn)
writer.start()
time.sleep(0.1)
try:
for attempt in range(1, 1001):
active = [name for name in sessions] # iterate while churn() mutates
print("no error this time")
except RuntimeError as e:
print(f"attempt {attempt}: RuntimeError: {e}")
finally:
stop.set()
writer.join()
attempt 176: RuntimeError: dictionary keys changed during iteration
Sometimes it fails on the 10th attempt, sometimes on the 500th, and the message can also be dictionary changed size during iteration. Lists don't raise an error at all: you just skip or repeat items silently.
Fix it by protecting both the writer and the reader with the same lock. To keep the critical section short, copy the data while holding the lock and do the slow work on the copy:
import threading
import time
sessions = {}
sessions_lock = threading.Lock()
stop = threading.Event()
def churn():
i = 0
while not stop.is_set():
with sessions_lock:
sessions[f"user{i}"] = time.time()
if len(sessions) > 1000:
sessions.pop(next(iter(sessions)))
i += 1
writer = threading.Thread(target=churn)
writer.start()
time.sleep(0.1)
for attempt in range(1, 1001):
with sessions_lock:
snapshot = list(sessions) # copy while holding the lock
active = [name for name in snapshot] # slow work happens outside the lock
print(f"{attempt} iterations without errors, {len(active)} active sessions")
stop.set()
writer.join()
1000 iterations without errors, 1000 active sessions
Note that the writer had to change too: its "insert, then maybe remove the oldest" is a two-step update that the reader must never see half done.
Lazy initialization
Creating an object on first use is a check-then-act race. Here eight threads call get_config() at the same moment. threading.Barrier holds them until all eight are ready, which makes the race show up reliably:
import threading
import time
class Config:
instances = 0
def __init__(self):
Config.instances += 1
time.sleep(0.01) # e.g. reading a file
self.values = {"debug": True}
_config = None
def get_config():
global _config
if _config is None: # several threads can see None here
_config = Config()
return _config
barrier = threading.Barrier(8)
def worker(results, i):
barrier.wait() # start all threads at the same moment
results[i] = get_config()
results = [None] * 8
threads = [threading.Thread(target=worker, args=(results, i)) for i in range(8)]
for t in threads:
t.start()
for t in threads:
t.join()
print("Config() called", Config.instances, "times")
print("distinct objects:", len({id(r) for r in results}))
Config() called 8 times
distinct objects: 8
The supposed singleton was created eight times, and different threads now hold different Config objects. If the object holds a connection pool or a cache, that's a real bug.
The usual fix is double-checked locking: check without the lock (fast, once the object exists), and if it's missing, take the lock and check again, because another thread may have created it while you waited for the lock:
import functools
import threading
import time
class Config:
instances = 0
def __init__(self):
Config.instances += 1
time.sleep(0.01)
self.values = {"debug": True}
_config = None
_config_lock = threading.Lock()
def get_config():
global _config
if _config is None: # fast path, no lock once initialized
with _config_lock:
if _config is None: # check again: another thread may have won
_config = Config()
return _config
@functools.cache
def get_config_cached():
return Config()
def run(fn):
Config.instances = 0
barrier = threading.Barrier(8)
results = [None] * 8
def worker(i):
barrier.wait()
results[i] = fn()
threads = [threading.Thread(target=worker, args=(i,)) for i in range(8)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"{fn.__name__}: Config() called {Config.instances} times, "
f"{len({id(r) for r in results})} distinct objects")
run(get_config)
run(get_config_cached)
get_config: Config() called 1 times, 1 distinct objects
get_config_cached: Config() called 8 times, 8 distinct objects
The second result is a common surprise. functools.cache and lru_cache are thread-safe in the sense that the cache itself never gets corrupted, but they don't hold a lock while your function runs. Threads that miss the cache at the same time all call the function. Use them for pure functions where an occasional duplicate call is harmless, not to guarantee "run exactly once".
If you can, create shared objects at import time or in main() before starting any threads. Then there's nothing to race on.
Races in asyncio
asyncio runs all tasks in one thread, so code between two awaits can't be interrupted. But every await is a point where other tasks run, and a check-then-act that spans an await races just like with threads:
import asyncio
balance = 100
async def check_fraud(amount):
await asyncio.sleep(0.01) # e.g. call a remote service
return True
async def withdraw(name, amount):
global balance
if balance >= amount: # check
if await check_fraud(amount): # other tasks run here
balance -= amount # act
print(f"{name}: withdrew {amount}, balance {balance}")
else:
print(f"{name}: insufficient funds")
async def main():
await asyncio.gather(withdraw("phone", 80), withdraw("laptop", 80))
print("final balance:", balance)
asyncio.run(main())
phone: withdrew 80, balance 20
laptop: withdrew 80, balance -60
final balance: -60
Both tasks checked the balance before either of them subtracted. asyncio.Lock makes the whole check-await-act sequence exclusive:
import asyncio
balance = 100
balance_lock = asyncio.Lock()
async def check_fraud(amount):
await asyncio.sleep(0.01)
return True
async def withdraw(name, amount):
global balance
async with balance_lock:
if balance >= amount:
if await check_fraud(amount):
balance -= amount
print(f"{name}: withdrew {amount}, balance {balance}")
else:
print(f"{name}: insufficient funds")
async def main():
await asyncio.gather(withdraw("phone", 80), withdraw("laptop", 80))
print("final balance:", balance)
asyncio.run(main())
phone: withdrew 80, balance 20
laptop: insufficient funds
final balance: 20
Without a lock, the rule is: any state you checked before an await may have changed after it, so check it again. Don't use threading.Lock in async code: it blocks the whole event loop. See Asyncio Module for more on tasks.
Races between processes
Processes don't share memory by default, but multiprocessing.Value, Array and Manager objects do, and they have the same read-modify-write problem. A Value comes with its own lock, available through get_lock():
import multiprocessing as mp
def work(counter, n):
for _ in range(n):
counter.value += 1 # read and write are separate steps
def work_locked(counter, n):
for _ in range(n):
with counter.get_lock(): # the lock that comes with the Value
counter.value += 1
if __name__ == "__main__":
for target in (work, work_locked):
counter = mp.Value("i", 0)
procs = [mp.Process(target=target, args=(counter, 50_000)) for _ in range(4)]
for p in procs:
p.start()
for p in procs:
p.join()
print(f"{target.__name__}: expected 200000, got {counter.value}")
work: expected 200000, got 68717
work_locked: expected 200000, got 200000
Processes really do run in parallel, so here the race shows up immediately and loses most of the updates. The lock built into Value only makes a single read or a single write safe; += still needs get_lock(). See Sharing State Between Processes.
File system races
The file system is shared by every thread, process and program on the machine, so check-then-act on files is a race even in a single-threaded script. This is often called TOCTOU: time of check to time of use.
import os
import tempfile
import threading
workdir = tempfile.mkdtemp()
path = os.path.join(workdir, "report.lock")
barrier = threading.Barrier(4)
winners = []
def claim_racy(name):
barrier.wait()
if not os.path.exists(path): # check
with open(path, "w") as f: # act: another thread may have created it
f.write(name)
winners.append(name)
def claim_atomic(name):
barrier.wait()
try:
with open(path, "x") as f: # create only if it doesn't exist, atomically
f.write(name)
winners.append(name)
except FileExistsError:
pass
for target in (claim_racy, claim_atomic):
winners.clear()
if os.path.exists(path):
os.remove(path)
threads = [threading.Thread(target=target, args=(f"t{i}",)) for i in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
with open(path) as f:
owner = f.read()
print(f"{target.__name__}: {len(winners)} thread(s) think they own it, file says {owner!r}")
claim_racy: 4 thread(s) think they own it, file says 't3'
claim_atomic: 1 thread(s) think they own it, file says 't3'
Mode "x" asks the operating system to create the file only if it doesn't exist, as a single atomic operation, so exactly one caller succeeds and the rest get FileExistsError. The general rule for files: don't ask first, just try the operation and handle the error:
try:
with open("data.txt") as f: # instead of: if os.path.exists("data.txt")
data = f.read()
except FileNotFoundError:
data = ""
The same applies to os.makedirs(path, exist_ok=True) instead of "check, then mkdir", and os.remove() wrapped in try/except FileNotFoundError instead of "check, then delete".
Atomic file writes
Writing a file with open(path, "w") first truncates it, so another process reading at the same time can see an empty or half-written file. Write to a temporary file in the same directory and rename it over the target with os.replace(), which replaces the file in one step:
import json
import os
import tempfile
def atomic_write_json(path, data):
directory = os.path.dirname(os.path.abspath(path))
# the temp file must be on the same file system as the target
fd, tmp_path = tempfile.mkstemp(dir=directory, suffix=".tmp")
try:
with os.fdopen(fd, "w") as f:
json.dump(data, f)
f.flush()
os.fsync(f.fileno()) # make sure the data is on disk
os.replace(tmp_path, path) # atomic rename over the old file
except BaseException:
os.remove(tmp_path)
raise
path = os.path.join(tempfile.mkdtemp(), "settings.json")
atomic_write_json(path, {"theme": "dark", "version": 1})
atomic_write_json(path, {"theme": "light", "version": 2})
with open(path) as f:
print(json.load(f))
print(os.listdir(os.path.dirname(path)))
{'theme': 'light', 'version': 2}
['settings.json']
Readers see either the complete old file or the complete new one, never a mix. On Windows, os.replace() fails with PermissionError if another process has the target file open at that moment, so retry in a short loop there.
Races in a database
When the shared data lives in a database, a Python lock doesn't help: other processes and servers access it too. Let the database do the check and the update in one statement:
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INTEGER)")
db.execute("INSERT INTO accounts VALUES (1, 100)")
db.commit()
def withdraw(conn, account_id, amount):
# check and act in one statement: the database does it atomically
cur = conn.execute(
"UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ?",
(amount, account_id, amount),
)
conn.commit()
return cur.rowcount == 1
print(withdraw(db, 1, 80))
print(withdraw(db, 1, 80))
print(db.execute("SELECT balance FROM accounts WHERE id = 1").fetchone())
True
False
(20,)
The racy version would be SELECT balance, compare in Python, then UPDATE. Other ways to do the same: unique constraints with INSERT ... ON CONFLICT, SELECT ... FOR UPDATE inside a transaction (PostgreSQL, MySQL), or a version column for optimistic locking.
Avoid sharing in the first place
The races you never have to fix are the ones where no data is shared. Give each worker its own data and combine the results in one place:
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
def count_words(text):
return Counter(text.split()) # works only on its own data
documents = [
"the cat sat on the mat",
"the dog sat on the log",
"a cat and a dog",
]
with ThreadPoolExecutor(max_workers=3) as pool:
partial_counts = pool.map(count_words, documents)
total = Counter()
for c in partial_counts: # combine in one thread
total += c
print(total.most_common(4))
[('the', 4), ('cat', 2), ('sat', 2), ('on', 2)]
Other ways to avoid sharing:
- Pass work and results through
queue.Queueso only one thread owns an object at a time. See Communicating between threads. - Use immutable data (tuples,
frozenset, frozen dataclasses). If nothing can change, nothing can race. - Use
threading.local()(orcontextvarsin async code) for per-thread state such as the current request:
import threading
import time
request = threading.local()
def handle(user):
request.user = user # each thread has its own request.user
time.sleep(0.01)
log("handled")
def log(msg):
print(f"[{request.user}] {msg}")
threads = [threading.Thread(target=handle, args=(u,)) for u in ("alice", "bob", "carol")]
for t in threads:
t.start()
for t in threads:
t.join()
[carol] handled
[alice] handled
[bob] handled
The order of the lines varies, but each thread always sees its own user. With a plain global variable, a thread could log another thread's user.
Finding races
Races are timing dependent, so a test that passes once proves little. Some techniques that help:
- Start threads together.
threading.Barrier(n)releases all threads at the same instant, as in the examples above. Without it, the first thread often finishes before the last one starts. - Widen the window. Temporarily put
time.sleep(0)or a short sleep between the check and the act, or between the read and the write. If the result changes, you found a race. - Repeat. Run the concurrent part thousands of times in a loop and check an invariant each time (the total balance, the number of objects created).
- Use real parallelism. Run your tests under the free-threaded build (
python3.13torpython3.14t) and withmultiprocessing; races that the GIL hides show up much faster. - Review the code. Look for every variable written by more than one thread or task, and every
ifthat is followed by an action on the same data. Each one needs a lock, an atomic operation, or a redesign.
Summary
- A race condition is a bug where the result depends on how concurrent work interleaves. Most are read-modify-write or check-then-act sequences.
- The GIL doesn't prevent races.
x += 1andd[k] = d.get(k, 0) + 1can lose updates; the free-threaded build makes such bugs more frequent. - Single operations on built-in types are safe; sequences of them are not. Prefer one-call operations like
setdefault(),queue.Queueanddeque. - Protect every read and write of shared data with the same lock, and keep the critical section short. Copy data under the lock before iterating over it.
- Use double-checked locking or eager initialization for singletons;
functools.cachedoesn't guarantee a single call. - In
asyncio, races happen atawait. Useasyncio.Lockor re-check state after awaiting. - For
multiprocessing.Value, useget_lock()around+=. - For files, try the operation and handle the error instead of checking first; use mode
"x"for exclusive creation andos.replace()for atomic writes. - In databases, let one SQL statement do the check and the update.
- Best of all, don't share mutable state: give workers their own data and combine results in one thread.