Modern C++ • C++20 baseline
Data Races, Atomics, and Memory Ordering
Use synchronization to establish both race freedom and the required visibility between threads.
Concurrent unsynchronized access to the same memory, when at least one access writes, is a data race and undefined behavior. Atomics make individual operations indivisible, but choosing memory order determines what other data those operations publish. Start with mutexes or sequentially consistent operations unless a measured need justifies weaker ordering.
Key points
- volatile is not a synchronization primitive.
- Relaxed atomics protect an atomic value but do not publish unrelated state.
Example
#include <atomic>
#include <thread>
std::atomic<int> completed{0};
void worker() {
completed.fetch_add(1, std::memory_order_relaxed);
}
int main() {
std::jthread first(worker);
std::jthread second(worker);
}
What to expect
Both increments are atomic; jthread destruction joins each worker before main exits.
Practice exercise
Protect a multi-field invariant with a mutex and compare it with a single atomic counter.
Key idea: Choose the simplest synchronization that correctly expresses the relationship between threads.