In C++, why does a worker thread spinning on while (!done) {} over a plain bool that another thread sets have undefined behaviour?
answer
- two rules, not one
- conflicting non-atomic accesses
- no happens-before between them
- loops may be assumed to end
- volatile is not atomic
basics
~20 sIt breaks two rules. The unsynchronized write and reads of a non-atomic bool are a data race, which is undefined behaviour; and a loop doing no I/O, volatile or atomic access may be assumed to terminate. Use std::atomic<bool>.
solid answer
~50 sTwo threads access the same `bool`, one writes, neither access is atomic and nothing makes one **happen before** the other: that is a **data race**, and the standard says any data race results in undefined behaviour. Separately, the **forward-progress** rule lets the implementation assume every thread eventually terminates, performs I/O, a `volatile` access or an atomic or synchronization operation; this loop does none of those. Together they let the compiler read `done` once, or drop the loop entirely: Apple clang 21 at `-O2` compiles the function to a bare `ret`. `volatile bool` satisfies forward progress but is still a data race. The fix is `std::atomic<bool>` with a release store and acquire loads, or a mutex with a condition variable. C++26 adds an exemption for trivial infinite loops like `while (true);`, which does not cover this one.
code
cpp · 18 lines#include <atomic>
#include <chrono>
#include <cstdio>
#include <thread>
std::atomic<bool> done{false}; // a plain bool here would be a data race
int main() {
std::thread worker([] {
while (!done.load(std::memory_order_acquire)) {
// atomic load each iteration: forward progress, no race
}
std::puts("worker saw done");
});
std::this_thread::sleep_for(std::chrono::milliseconds(10));
done.store(true, std::memory_order_release);
worker.join();
}go deeper
Remember that sharing a plain variable between threads without std::atomic or a mutex is a bug even when one thread only reads.
Define a data race the standard's way: conflicting accesses, at least one non-atomic, no happens-before; and say why volatile does not fix it.
Explain the second rule, forward progress, show the compiler deleting the loop, and fix it with an atomic or a condition variable depending on whether spinning is acceptable.
Treat every so-called benign race as undefined in review policy, and decide which synchronization primitive a codebase standardises for stop flags.
## Rule one: a data race is undefined behaviour The standard defines a **data race** precisely. Two actions **conflict** when they access the same **memory location** and at least one of them modifies it. A program execution contains a data race if it contains two potentially concurrent conflicting actions, at least one of which is not atomic, and neither **happens before** the other. Its verdict is one sentence: any such data race results in undefined behaviour. Applied to the flag: - The writer's `done = true;` and the worker's reads of `done` touch the same memory location, and one is a write, so they conflict. - They run on different threads, so they are potentially concurrent. - A plain `bool` is not atomic, and no mutex, atomic or thread start or join orders the write before any particular read. That is a data race, so the whole execution has undefined behaviour. "Benign" races do not exist in the standard's model: the rule makes no exception for a "harmless" flag or statistics counter. A **memory location** is a scalar object, or a maximal run of adjacent non-zero-width bit-fields. Two threads writing different elements of one `char` array do not race, but two threads writing neighbouring bit-fields in one `struct` do. ## Rule two: forward progress The second rule lets the implementation assume that any thread will eventually do one of the following: 1. terminate; 2. call `std::this_thread::yield` (listed since C++26); 3. call a library I/O function; 4. access an object through a `volatile` glvalue; 5. perform an atomic or synchronization operation (C++26 excludes its new atomic modify-write operations, such as `std::atomic_store_add`); 6. keep executing a **trivial infinite loop** (C++26). `while (!done) {}` over a plain `bool` does none of them, so the compiler may assume it ends. Combined with rule one, which lets it assume no other thread changes `done` while the loop runs, the loop either exits at once or never needed to run. Apple clang 21 at `-O2` turns `void wait_plain() { while (!done) {} }` into a single `ret` instruction; with `std::atomic<bool>` it emits a load-acquire loop. ## Why volatile is not the fix | Flag type | Forward progress | Data race | Verdict | |---|---|---|---| | `bool` | not satisfied | yes | undefined | | `volatile bool` | satisfied by the volatile access | yes, volatile is not atomic | undefined | | `std::atomic<bool>` | satisfied by the atomic load | no | well-defined | | `bool` guarded by a `std::mutex` | satisfied by lock operations | no | well-defined | `volatile` stops the compiler from caching or removing the accesses, so the loop often "works" in testing, but the standard still calls the unsynchronized access a race, and `volatile` provides no ordering for the data the flag is meant to publish. ## C++26's trivial infinite loops C++26 defines a **trivially empty iteration statement**, such as `while (expr) ;` or `for (init; ; ) {}`, and calls it a **trivial infinite loop** when its controlling expression is a constant expression that evaluates to `true`. Its body is replaced with a call to `std::this_thread::yield`, so `while (true);` in firmware's idle path is no longer undefined. `while (!done) {}` is not covered, because `!done` is not a constant expression, and the data race remains in any case. ## The fix - Declare the flag `std::atomic<bool>` and use `store(true, std::memory_order_release)` with `load(std::memory_order_acquire)`, or the default sequentially consistent operations. - If the worker should sleep rather than spin, use a `std::mutex` with a `std::condition_variable`, or `std::jthread` and `std::stop_token` in C++20. - Look for the same pattern in "statistics" counters incremented from several threads; they need `std::atomic` or a lock too. - In C++20, `std::atomic_flag` and `std::atomic<bool>` also offer `wait` and `notify_one`, which block instead of burning a core. - Signal handlers are the one place where a plain-looking type is allowed: two accesses to a `volatile std::sig_atomic_t` object in the same thread do not race even if one occurs in a signal handler. That exception does not extend to other threads. Memory orders, condition variables and stop tokens have their own lessons; the point here is that both the race and the empty loop are undefined before any of those details matter.
- Do two threads writing different members of the same C++ struct race?Not if the members are separate memory locations: each scalar member is its own location, so writing `s.a` on one thread and `s.b` on another is not a data race, though it may cause false sharing. The exception is bit-fields: a maximal run of adjacent non-zero-width bit-fields is one memory location, so two threads writing neighbouring bit-fields do race.
- Is while (true); still undefined behaviour in C++26?No. C++26 calls a trivially empty loop whose controlling expression is a constant expression evaluating to `true` a trivial infinite loop, replaces its body with a call to `std::this_thread::yield`, and adds it to the forward-progress list. Before C++26 such a loop could be assumed to terminate. A loop whose condition reads a variable, like `while (!done) {}`, is not covered.
- A race on a bool flag is benign because a bool write is a single instruction.
- Declaring the flag volatile makes the cross-thread access well-defined.
- The loop works on x86 in testing, so the code has no undefined behaviour.
- Only simultaneous writes can race; one writer and one reader are always safe.
- C++26 made every infinite loop without side effects well-defined.
Assumes C++23; C++26 adds std::this_thread::yield to the forward-progress list and makes trivial infinite loops such as while (true); well-defined.