Part 4 of 7 · 2 min read
Data races
Think of it this way. A shared whiteboard with two people writing on it at the same time can end up with a mixture of both texts. If the rules say that any such mixture is allowed to do anything, even to make the building fall, then no plan can rely on it. The analogy stops in one place: the whiteboard shows a blurred text, and a data race in C allows the compiler to produce code that no ordering of the source could explain.
In plain words: A data race occurs when two threads access the same memory location at the same time, at least one of the accesses is a write, and nothing orders the two accesses (no lock, no atomic operation). The C standard makes a program with a data race undefined behaviour: it promises nothing about the result. A race is not just "an unpredictable value". The compiler is allowed to assume that there are no races, and it optimises on that assumption.
A demonstration. The program waits for a flag that another thread sets after 100 ms:
static int done; /* plain int, shared */
void *setter(void *a) { usleep(100000); done = 1; return NULL; }
...
while (!done) ; /* wait for the other thread */
The compiler sees a loop that never changes done and reads it once, then loops for ever. Results:
gcc -O2, plain int : still running after 3 s (the program hangs)
gcc -O0, plain int : saw the flag
gcc -O2, atomic_int : saw the flag
The program works at -O0 and hangs at -O2, with the same source. Each of the three is a correct reading of the C rules, except that the first is the result of a data race. This shows why "benign" races (a flag that is only ever set once, a statistics counter that does not need to be exact) are not safe in C: they depend on the compiler. Use atomic_int (<stdatomic.h>) or a lock for every shared variable that more than one thread touches while any thread writes.
Remember page 1: volatile stops the compiler from dropping the read, but it does not order accesses and does not make them atomic. For a flag, use an atomic.
Data race
A data race is a situation in which two threads access the same memory location without ordering by synchronisation, at least one of them writing, and which the C standard defines as undefined behaviour for the whole program.
Example: a plain int flag written by one thread and polled by another can make an optimised loop never end.
Check yourself:
1. What three conditions make a data race?
2. Why did the same source hang at -O2 and work at -O0?
3. Why is "it is only a flag" not a safe excuse?