Topic 007 / Core
Race conditions, deadlocks and thread safety
Chapter 1.3 · Concurrency and Thread Safety
What and why
The moment two threads touch the same mutable state without coordination (→ 6), the program's correctness starts to depend on timing it doesn't control — a race condition. Fixing races with locks introduces a new risk: if two threads can each wait for a lock the other holds, neither ever proceeds — a deadlock. This topic is the minimum toolkit for making shared state safe: mutual exclusion, atomic operations, and lock discipline. Builds on: → 6 (concurrency and parallelism).
Diagram
| Hazard | Symptom | Fix |
|---|---|---|
| Race condition | lost or corrupted update | mutex around the critical section, or an atomic operation |
| Deadlock | threads frozen, waiting on each other forever | consistent lock ordering, or a timeout |
| Livelock | threads keep running but make no progress | backoff instead of immediate retry |
| Starvation | one thread never gets scheduled | fair scheduling / bounded wait |
How it works
- A race condition happens when a critical section — code that must execute as if no one else can see it mid-way — runs on shared state without protection.
- A mutex (lock) makes a critical section exclusive: only one thread executes it at a time. A hardware atomic operation (e.g., compare-and-swap) does the same for one simple operation without ever blocking a thread.
- A deadlock requires four conditions at once: mutual exclusion, threads holding one resource while waiting for another, no preemption, and a circular wait. Breaking any one condition prevents it — consistent lock ordering removes the circular wait.
- A timeout on lock acquisition turns a silent, permanent freeze into a detectable, recoverable failure.
- The fewer places shared mutable state is touched, and the shorter each critical section is, the fewer races and deadlocks there are to find — minimizing shared state is a design choice, not just a bug fix.
Practical example
(illustrative). Two threads each increment a shared counter
100,000 times with no locking. Expected total: 200,000. Because increment is really
read-then-write-back, two threads can both read the same value before either writes it
back, and one increment is lost; the observed total comes out lower than 200,000 and
differs run to run. Wrapping the increment in a mutex makes every run total exactly
200,000, at the cost of each thread sometimes waiting. Replacing the mutex with a single
atomic increment also totals exactly 200,000, typically with higher throughput than the
mutex version, because a thread never blocks waiting for another to release a lock — only
for the one hardware instruction to complete.
When to use it
- Use explicit synchronization whenever: two or more threads read and write the same mutable state.
- Avoid: one lock guarding unrelated state "to be safe" — a lock that's too coarse serializes work that never needed to wait on each other, erasing the benefit of having multiple threads at all.
- Failure scenarios: inconsistent lock ordering across two different code paths producing a deadlock that only appears under load; a "fixed" race that just shrank the unsafe window instead of closing it (check-then-act bugs); naive immediate retry after a failed lock attempt producing livelock instead of progress.
- Simpler alternative: avoid shared mutable state in the first place — message passing or immutable data structures remove the hazard rather than guarding against it. The same problem reappears later at larger scale as database concurrency control (→ 71) and distributed locks (→ 137).
Practice
(mechanism — build a tiny version, predict then verify; 20–30 min, no lab services).
- Make two threads each increment a shared counter, unlocked, 100,000 times; run it three times and record the (likely wrong, likely different) totals.
- Fix it with a mutex; confirm the total is exactly 200,000 on every run; measure throughput.
- Fix it again with an atomic increment instead of a mutex; confirm correctness; measure throughput and compare it to the mutex version.
- Predict, then verify: write two threads that each acquire two shared locks in opposite order; show the deadlock; fix it by making both threads acquire the locks in the same order.
Done when the unlocked version visibly loses updates across repeated runs, both fixes are provably correct across repeated runs, and the deadlock is first reproduced, then eliminated by reordering.
Key takeaway
Unprotected shared state races; protected-but-careless shared state can deadlock — lock the smallest section, order locks consistently, or avoid the sharing altogether. Done when you can: reproduce a lost update, fix it two different ways, and reproduce then fix a deadlock. Used next in → 71 (database concurrency control), → 137 (distributed locks and leases).
References
None — this topic makes no external claims.
Source directory