Definition
A race condition is a flaw in a program whose activities overlap in time, such as two threads (sequences of instructions that share memory) or a thread and an interrupt handler §6.12: whether the program behaves correctly depends on the order in which their steps happen, and at least one order the program allows gives a wrong result. A data race §9.3 is narrower: two unsynchronized accesses to the same memory location, at least one a write. A program can have a race condition without any data race.
The idea
A bank allows a withdrawal only if the balance covers it. The code checks that balance is at least the amount, then subtracts the amount. A careful programmer guards every read and every write of balance with one lock, so no two accesses ever overlap. Two withdrawals of 80 from a balance of 100 can still both succeed and leave . Each check was true when it was made. It was no longer true when the subtraction that relied on it ran, because the other withdrawal had subtracted in between.
The picture is two people who both read a sign saying one seat left and both walk to the seat. The sign was correct when each of them read it. The error lies in the gap between reading the sign and sitting down. A decision based on shared state stays valid only while that state stays unchanged, and a race condition is a gap of this kind that another activity can fill. Making each single access safe does nothing about the gaps between accesses. The picture stops at one point: a person notices that the seat is taken, while a program acts on its earlier reading without looking again.
How it works
The steps can be memory accesses, file operations, messages or device commands. Most race conditions take one of three shapes.
Lost update. Two activities each read a value, compute a new value from it, and write it back. The second write discards the first, so two increments of one counter can raise it by one instead of two.
Check-then-act. An activity tests a condition and then acts on the assumption that the condition still holds, while another activity changes it in between. When the shared state is a file and an attacker can fill the gap, the flaw is called time-of-check to time-of-use §9.26 (TOCTOU). In the classic case, a privileged program checks that a user may write to a file name, an attacker then replaces that name with a link to a protected file, and the program opens the protected file.
Order violation. One activity assumes that another has already done something, such as filling a buffer before an interrupt handler reads it, but nothing enforces that order.
To find and repair a race condition, work through four steps.
State the invariant: the condition that must hold whenever no operation is in progress. For the bank,
balanceis never negative.Find the whole operation that must preserve the invariant: everything from the first read whose result feeds a decision to the last write that depends on that decision. For a withdrawal, that is from reading
balancefor the check to writing the reducedbalance.List every other activity that can change the same state during that operation: other threads, interrupt handlers, other processes, other machines.
Make the whole operation indivisible with respect to all of them. Either hold one lock from the check to the last write, so that one critical section §9.4, a region that the lock lets only one activity enter at a time, covers both; or make the write conditional on the state still being what the check saw. A compare-and-swap §9.9, an atomic instruction that writes a new value only if memory still holds an expected value, does this; when it fails, the operation starts again from the read.
Race conditions are hard to find by testing, because the bad order may need two events to fall within a few instructions of each other. Adding logging changes the timing and can hide the failure. Long stress runs with many activities, tools that force unusual orders, and model checking §3.30, which explores every order of the steps of a small model of the program, find more of them than ordinary tests do.
Worked example
balance starts at 100. Threads A and B each withdraw 80. Every access to balance holds the lock L, but each thread releases L between its check and its subtraction:
A locks
L, reads 100, finds true, and unlocks.B locks
L, reads 100, finds true, and unlocks.A locks
L, reads 100, writes , and unlocks.B locks
L, reads 20, writes , and unlocks.
No two accesses overlapped and every access held the lock, yet the invariant is broken: both checks approved spending the same 80 of the 100. Had B instead subtracted from the 100 it read in step 2, it would have written 20, and the bank would have paid out 160 while recording only 80. The same race then appears as a lost update.
Repair with one critical section. A locks L, reads 100, finds true, writes 20, and unlocks. B locks L, reads 20, finds false, refuses, and unlocks. The final balance is 20 whichever thread goes first.
Repair with compare-and-swap and no lock. A and B both read 100 and both find true. A performs a compare-and-swap on balance with expected value 100 and new value 20; balance holds 100, so the write succeeds. B performs the same compare-and-swap; balance now holds 20, not the expected 100, so nothing is written and B is told so. B starts again: it reads 20, finds false, and refuses. The final balance is again 20.
Stated precisely
A program has a race condition when two executions that its synchronization allows, which differ only in the order of steps of concurrent activities, produce results of which at least one violates the program’s specification.
For a check-then-act operation, let be the condition that the check tests, here , and suppose the action preserves the invariant only if still holds when the action runs. The operation is free of the race when no step of another activity that can make false can occur between the check and the action. Two designs establish this.
Mutual exclusion: the check and the action lie in one critical section, and every activity that can change the state enters through the same lock.
Validation at the action: the action itself tests the state and takes effect only if the state is unchanged, in one atomic step, as compare-and-swap does; a failed attempt is repeated from the check.
Linearizability, the correctness condition that Herlihy and Wing defined in 1990, states the goal: each operation must appear to take effect at a single instant, its linearization point §8.6, between its start and its end. Locking every access gives each single read and write such an instant, but gives the withdrawal two instants, one for the check and one for the subtraction, with a gap between them. The withdrawal as a whole is therefore not linearizable, which is the race condition.
The withdrawal program with a lock on every access has no data race, because the same lock orders §9.15 every pair of accesses, and it still has a race condition. Freedom from data races and freedom from race conditions are different properties.
Limits and common mistakes
Locking every access is not enough. The lock must cover the whole decision, from the check to the action.
Holding a lock longer has costs. Other activities wait longer, and a critical section that takes a second lock risks deadlock §9.14, in which two activities each wait for a lock that the other holds.
A clean report from a data race detector such as ThreadSanitizer §10.25 shows only that no data race occurred in the executions it watched. It says nothing about race conditions in the program’s logic, such as the withdrawal above.
Not every dependence on timing is a flaw. If every possible order gives an acceptable result, as with two log lines that may appear in either order, there is no race condition. Deciding which results are wrong requires a specification.
Race conditions are not limited to memory. Files, database records, device state, network messages and processes on different machines can all be the shared state.
Passing tests do not show that a race condition is absent. The bad order may occur once in millions of runs, and it may appear only on faster hardware, under heavier load or with a different compiler.
Questions answered
Can two separately locked operations still form a check-then-act race?
Yes. If the check holds a lock and releases it, and the action takes the lock again later, another activity can change the shared state in the gap between the two locked regions, so the action runs on a condition that is no longer true. Example: a balance of 100 and two withdrawals of 80. Both threads check under the lock and both release it; then both subtract, and the balance ends at . Every access was locked and there was no data race, but the check and the action did not form one indivisible operation.
There are two repairs. Hold one lock from the check through the action, so that the condition checked is still true when the action runs. Or make the action itself conditional with a compare-and-swap, an atomic instruction that writes only if the state is still the value the check saw, and repeat the check when the compare-and-swap fails. In both cases, first state the invariant, here that the balance never becomes negative, and the whole operation that must preserve it.
Related entries: Data race (§9.3), Critical section (§9.4), Time-of-check to time-of-use (TOCTOU) (§9.26), Linearization point (§8.6), Compare-and-swap (§9.9). Further reading: [85].