C++ · 6 · Concurrency28 / 36 · 78%
std::atomic & Memory Order
Data races are undefined behavior; atomics are how you avoid them without a mutex.
Examples: atomic<int>, fetch_add, compare_exchange
shortcuts: ← prev · → next · M mark
1
Atomic Counters
The right tool for a shared counter.
Example
example
std::atomic<int> hits{0};
hits.fetch_add(1, std::memory_order_relaxed);
int now = hits.load();
std::atomic<bool> ready{false};
ready.store(true, std::memory_order_release);concurrent increments, one consistent total
2
Acquire / Release
Release publishes everything written before it; acquire sees it.
Example
example
// producer
data = compute();
flag.store(true, std::memory_order_release);
// consumer
while (!flag.load(std::memory_order_acquire)) { }
use(data); // guaranteed to see the producer's write3
CAS Loops
compare_exchange is how you build lock-free updates.
Example
example
std::atomic<int> best{0};
int cur = best.load();
while (candidate > cur &&
!best.compare_exchange_weak(cur, candidate)) {
// cur was refreshed with the current value; loop and retry
}4
Guidance
Lock-free is not automatically faster.
Interview question
Is std::atomic<T> always lock-free?
TIP
Default to seq_cst ordering. Weaken only with a benchmark proving it matters.