What is a data race, and how does the C++ standard define its consequences?
Last updated
A data race is two threads accessing the same memory location, at least one writing, with no synchronization ordering them and not both atomic.
The standard makes the whole program undefined behavior, so the compiler may assume races never occur. Results include torn or stale values, crashes and nondeterministic bugs.
Avoid it with
std::mutexorstd::atomic(concurrent reads of immutable data are fine). ThreadSanitizer detects races at runtime.
- https://dev.to/kprotty/understanding-atomics-and-memory-ordering-2mom
- https://www.geeksforgeeks.org/cpp/data-races-in-cpp/
- https://en.wikipedia.org/wiki/Race_condition
- https://stackoverflow.com/questions/48109271/does-this-example-contain-a-data-race
- https://stackoverflow.com/questions/75857905/c-multithread-joining-only-working-on-the-first-thread-but-not-working-for-oth
- https://github.com/indy256/Full-stack-Developer-Interview-Questions-and-Answers/blob/master/README.md
- https://www.open-std.org/jtc1/sc22/WG21/docs/papers/2009/n2955.html
- https://www.modernescpp.com/index.php/race-condition-versus-data-race/