C++ › Undefined Behavior

What is a data race and why is it undefined behavior?

Advanced

Answer

A data race occurs when two or more threads access the same memory location concurrently, at least one access is a write, and there's no synchronization ordering them. The C++ memory model declares data races undefined behavior because the result depends on unpredictable timing and CPU/compiler reordering. Prevent them with mutexes, atomics, or by not sharing mutable state.
// two threads doing counter++ without a mutex/atomic: data race (UB)
Real-world example An unsynchronized shared counter produces wrong totals and intermittent crashes—classic data-race UB.

Common follow-ups: What three conditions define a data race? | How do you prevent one?