Section 9.3

Data race

Definition

A data race is a fault defined by the C and C++ language standards: two threads, sequences of instructions that run concurrently and share memory, access the same memory location; at least one access writes; at least one is not an atomic operation §9.8; and the happens-before relation §9.10, the order that synchronization such as a lock creates between threads, places neither access before the other. The C standard says that a data race causes undefined behavior §4.12: it places no requirement at all on what the program then does.

The idea

Compilers and processors make programs fast by reordering, merging and removing memory accesses. A compiler keeps a variable in a register instead of loading it again; a processor completes two independent stores in whichever order is cheaper. Within one thread these changes cannot be seen. Another thread that watches the same variables can see them. The C and C++ standards settle the conflict with a contract. The programmer marks every access through which threads communicate, using atomic operations or locks. The compiler and the processor may then transform every unmarked access freely, as if no other thread were looking.

A data race is a broken contract: an unmarked access that another thread does watch. The standard does not try to say which values such a read may return, because the answer would depend on every optimization of every compiler and processor; it declares the behavior undefined. In exchange, a program without data races that uses only locks and the default atomic operations behaves as if the steps of its threads were interleaved in a single order, the intuitive model. This guarantee is often called sequential consistency §9.12 for data-race-free programs.

How it works

The definition uses four terms of the C standard.

To check a shared access for a data race, pair it with each other access to the same variable and ask five questions.

  1. Do the two accesses touch the same memory location?

  2. Are they made by different threads?

  3. Does at least one of them write?

  4. Is at least one of them not atomic?

  5. Is there no chain of happens-before edges from one access to the other?

Five yes answers mean a data race. A single no means that this pair is not a data race.

Worked example

Thread P prepares a value and announces it; thread Q waits for the announcement and then uses the value. Both variables are plain int and start at 0:

P: data = 42; ready = 1;
Q: while (ready == 0) { } use(data);

P writes ready and Q reads it, neither access is atomic, and nothing orders them: a data race. The accesses to data form a second one. Two outcomes that real compilers and processors produce show why the standard calls this undefined. The compiler may load ready once before the loop and keep it in a register, because no code of Q’s own changes it inside the loop, and then Q loops forever. Or the compiler or the processor may perform P’s two stores in the other order, because they are independent, and then Q can see ready equal to 1 and still read 0 from data.

The repair makes ready an atomic variable. P stores 1 into it with a release store, and Q loads it with acquire loads until it reads 1; in C these are atomic_store_explicit with memory_order_release and atomic_load_explicit with memory_order_acquire. This pairing is called acquire-release ordering §9.11. Number the four accesses: (1) P writes 42 to data; (2) P stores 1 to ready; (3) Q loads ready and reads 1; (4) Q reads data. Then (1) is sequenced before (2); (2) synchronizes with (3), because (3) is an acquire load that reads the value the release store (2) wrote; and (3) is sequenced before (4). By the chain, (1) happens before (4), so the pair (1) and (4) fails question 5 and is not a data race, and Q reads 42. The accesses to ready are all atomic, so they fail question 4. The program has no data race.

Now let Q use a relaxed load, memory_order_relaxed, which is atomic but creates no synchronizes-with edge. The accesses to ready are still not a data race, because both are atomic. But no edge now links (2) to (3), so nothing places (1) before (4), and the accesses to data form a data race again, even though Q did read the 1.

A data race can even produce a value that no thread ever wrote. On a 32-bit processor, a compiler usually stores a 64-bit variable with two 32-bit stores. Let a 64-bit counter hold 0x00000000FFFFFFFF, which is 232−1=4,294,967,2952^{32} - 1 = 4{,}294{,}967{,}295. One thread adds 1, giving 0x0000000100000000, which is 232=4,294,967,2962^{32} = 4{,}294{,}967{,}296, and stores the low half first. A thread that reads between the two stores gets the new low half 0x00000000 and the old high half 0x00000000, so it reads 0. With the stores in the other order it would read 0x00000001FFFFFFFF, which is 233−1=8,589,934,5912^{33} - 1 = 8{,}589{,}934{,}591.

Stated precisely

The C11 standard, ISO/IEC 9899:2011, states in section 5.1.2.4: “The execution of a program contains a data race if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other. Any such data race results in undefined behavior.” Two evaluations conflict “if one of them modifies a memory location and the other one reads or modifies the same memory location.” The C++ standard, from C++11 on, defines data races in the same way.

Leaving aside the rarely used consume ordering, happens before is the smallest relation that contains sequenced before, the order of evaluations within one thread, and synchronizes with, and that is transitive. The main synchronizes-with edges of C11 are these. An atomic store with release ordering on an object synchronizes with an atomic load with acquire ordering on the same object that reads the stored value. Every earlier mtx_unlock of a mutex synchronizes with a later mtx_lock of that mutex. The completion of thrd_create synchronizes with the start of the new thread. The end of a thread synchronizes with the return of the thrd_join call that waits for it.

Note 12 of the same section gives the guarantee that makes the rule worthwhile: programs that use mutexes and sequentially consistent atomic operations (the default ordering) to prevent all data races, and use no other synchronization operations, behave as though the operations of their threads were simply interleaved.

The standard defines data races only between threads, and an interrupt handler §6.12 is not a C thread. The nearest construct in the standard is a signal handler. Section 5.1.2.3 says that, when a signal interrupts the program, the values of objects that are neither lock-free §9.13 atomic objects nor of type volatile sig_atomic_t are unspecified. Data shared with an interrupt handler therefore relies on rules that the compiler and the platform document. In practice it uses lock-free atomic objects, or interrupt §6.11 masking together with compiler barriers §4.37.

Limits and common mistakes

No data race does not mean correct. A program whose every shared access is atomic, or locked, can still check a condition in one step and act on it in another; the race condition §9.2 entry gives an example.

Hardware that reads and writes a 32-bit word indivisibly does not remove a data race. The rule also constrains the compiler, which may delete, repeat, merge or move a plain access, as the loop above shows, whatever the hardware does.

The volatile qualifier §4.34 does not prevent a data race. A volatile access is performed as written, but it is not atomic and creates no happens-before edge between threads.

A relaxed atomic access prevents a data race on its own variable only. It orders no other data.

C and C++ have no benign data races. Code that only reads a flag, or that only ever writes the same value, without atomic operations still has undefined behavior, and compiler optimizations §3.39 have broken such code in practice.

Other languages draw the line elsewhere. In Java, a program with data races still has defined, though weak, semantics. Safe Rust rejects data races when the program is compiled.

ThreadSanitizer §10.25, a race detector built into the Clang §12.17 compiler, reports the data races that occur in the executions it observes, by tracking happens-before edges. It cannot report a race on a path that the test never ran, and it watches threads on an ordinary operating system, so it knows nothing of interrupt handlers on a microcontroller §6.1.

Questions answered

Which happens-before edge protects the shared read?

The shared read is protected by a chain of happens-before edges from the last write of the shared data to the read, and the chain must contain a synchronizes-with edge from the writing thread to the reading thread. Happens before is the order that the C and C++ standards build from program order inside each thread and from synchronization between threads. Without such a chain, a non-atomic read and a write of the same location in different threads form a data race, which has undefined behavior.

In the release-acquire pattern, the synchronizes-with edge runs from the writer’s release store to a flag to the reader’s acquire load that reads the stored value. The whole chain is: the write of the data is sequenced before the release store; the release store synchronizes with the acquire load; the acquire load is sequenced before the read of the data. With a mutex, the edge runs from the writer’s unlock to the reader’s later lock of the same mutex, with the write inside the writer’s critical section §9.4 and the read inside the reader’s. None of these creates the edge: a relaxed atomic load, a volatile variable, a delay or sleep, or the observation that the read usually happens later in time.

Related entries: Happens-before relation (§9.10), Acquire-release ordering (§9.11), Race condition (§9.2), Volatile qualifier (§4.34), Undefined behavior (UB) (§4.12), Sequential consistency (§9.12), ThreadSanitizer (§10.25). Further reading: [78, 79, 106].