What is a data race and why is it undefined behavior?
Short 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.
Advertisement
AModel 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.
Example
// 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.
Likely follow-ups
- What three conditions define a data race? | How do you prevent one?
Related topics