Expose a Lost Update with a Controlled Race
Core idea
A race condition occurs when correctness depends on the interleaving of concurrent operations. A read-compute-write sequence is not a single atomic transaction. Two threads can read the same old value, compute independently and overwrite each other. The barrier below deliberately forces the stale reads, without relying on scheduling luck.
from threading import Thread, Barrier, Lockstate = {'count': 0}ready = Barrier(2)write_lock = Lock()def increment(): old = state['count'] ready.wait() with write_lock: state['count'] = old + 1workers = [Thread(target=increment) for _ in range(2)]for t in workers: t.start()for t in workers: t.join()print(state['count'])Both workers read zero before either writes. Even serialized writes lose one update.
Expected output:
1Protect the entire update
from threading import Thread, Lockstate = {'count': 0}lock = Lock()def increment(): with lock: state['count'] += 1workers = [Thread(target=increment) for _ in range(2)]for t in workers: t.start()for t in workers: t.join()print(state['count'])The lock covers the read and write together.
Expected output:
2Common mistake
Do not rely on the GIL or a successful stress run as proof of atomic compound operations. Lock every access that participates in the same invariant.
Practice
Trace both reads and writes on paper, then compare with a critical section. Explain why moving the barrier inside the lock would block progress.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Race conditions
Check your understanding of race conditions.
What is printed?
old_a=0; old_b=0count=old_a+1count=old_b+1print(count)What is printed?
from threading import Locklock=Lock()with lock: print(lock.locked())print(lock.locked())Why is locking only the write insufficient?
What demonstrates a race without timing guesses?