Concurrency · intermediate
Race condition
A race condition exists when a system's correctness depends on the relative timing or ordering of events that are not adequately coordinated.
Why it matters
Races can silently corrupt state or violate authorization and are often intermittent because different schedules expose different outcomes.
Mental model
How to reason about race condition
List the operations that must appear indivisible, then imagine pausing between every pair of steps. If another actor can enter and invalidate an assumption, there is a race window.
Analogy
Two editors download the same document, make separate changes, and save; the later save can overwrite the earlier work because neither coordinated against the shared version.
Examples
See the boundary, not just the happy path
Worked example · Lost update
A reads 0; B reads 0; A writes 1; B writes 1Two intended increments produce a final value of one because the read-modify-write sequences interleave.
Worked example · Time-of-check to time-of-use
check path permissions, then open the pathIf another actor can replace the path between check and open, the checked object may differ from the used object.
Useful contrast · Benign nondeterminism
two independent log messages appear in either orderUnpredictable ordering is not itself a bug when every permitted order satisfies the program's correctness requirements.
Common mistakes
Misconceptions to remove early
Adding a sleep to force an order
A delay changes probabilities rather than establishing a happens-before relationship. Different load or hardware can reopen the race.
Equating every race condition with a data race
A data race is a specific unsynchronized memory-access condition. Higher-level races can occur through files, messages, transactions, or separately synchronized operations.
Quick check
Can you predict the result?
1. Why can count = count + 1 lose an update across threads?
- • It is a read-modify-write sequence whose steps can interleave
- • Integer addition is always random
- • The assignment necessarily creates a new process
2. What turns nondeterministic ordering into a race condition?
Keep building