In C++, when is memory_order_relaxed enough for an atomic statistics counter, and what exactly does relaxed give up?
answer
- still atomic, still no lost updates
- orders nothing else
- one modification order per atomic
- join makes the total visible
- never a ready flag
basics
~20 sRelaxed is enough when the counter's value is the only thing anyone needs: increments stay atomic and none are lost. It gives up ordering of all other memory, so a relaxed counter must never signal that other data is ready.
solid answer
~50 sA relaxed `fetch_add` is still a full atomic read-modify-write: it reads the latest value in the counter's modification order, so no increment is lost, and every thread agrees on that one order of values for the counter. What `memory_order::relaxed` drops is **ordering of other memory** — the operation creates no synchronizes-with edge, so seeing the counter reach 1000 tells a thread nothing about any other variable. That fits statistics, hit counts and unique-id generators, read after `join()` (which itself synchronises with the thread's completion) or read approximately while running. It is wrong the moment a reader infers something from the value, such as "count reached N, so the results are written". On x86-64 a relaxed and a seq_cst `fetch_add` compile to the same `lock` instruction with clang; the saving shows on weakly ordered CPUs and in compiler freedom.
code
cpp · 18 lines#include <atomic>
#include <cstdint>
#include <cstdio>
#include <thread>
#include <vector>
std::atomic<std::uint64_t> buffers_mixed{0}; // statistics only: nothing else hangs off it
int main() {
std::vector<std::thread> workers;
for (int t = 0; t < 4; ++t)
workers.emplace_back([] {
for (int i = 0; i < 250000; ++i)
buffers_mixed.fetch_add(1, std::memory_order_relaxed);
});
for (auto& w : workers) w.join(); // join() is what makes the final total visible
std::printf("%llu\n", static_cast<unsigned long long>(buffers_mixed.load(std::memory_order_relaxed)));
}go deeper
Recall that a relaxed fetch_add still counts correctly; only its effect on other memory is weaker than the default seq_cst.
Explain modification order and the absence of synchronizes-with, and list where relaxed fits: statistics, id generators, reference-count increments, totals read after join.
Spot the relaxed done-counter used as a ready signal, explain the resulting data race, and know that x86-64 emits the same locked instruction either way.
Set a rule that relaxed needs a comment saying why nothing depends on ordering, and keep the seq_cst default where reviewers cannot verify that claim.
## What `memory_order::relaxed` keeps Every atomic operation takes a `std::memory_order` argument, and the default is `memory_order::seq_cst`. Passing `memory_order::relaxed` keeps the parts of atomicity a counter needs: - **Indivisibility.** The standard's note on relaxed operations says an implementation must still make each atomic access indivisible with respect to all other atomic accesses to that object. - **No lost updates.** A read-modify-write such as `fetch_add` always reads the last value in the object's **modification order** — the single total order of all writes to that atomic object. Four threads doing 250,000 relaxed increments each end at exactly 1,000,000. - **Per-object coherence.** All threads observe the counter's values in an order consistent with that modification order; a thread never sees the counter go backwards. ## What it gives up `memory_order::relaxed` is defined as "no operation orders memory". A relaxed operation never takes part in a **synchronizes-with** relationship, so it does not make **other** writes visible. Concretely: - Writes made before a relaxed increment can become visible to another thread after the new count does. - A thread that reads `count == 1000` with a relaxed load learns nothing about any other variable. - Different relaxed atomics are not ordered with each other: two threads may see updates to two counters in opposite orders. ## Where relaxed is the right choice | Use | Relaxed? | Why | |---|---|---| | Statistics: frames mixed, buffers dropped, cache hits | yes | only the number matters | | Unique id generator, `next_id.fetch_add(1)` | yes | read-modify-write guarantees distinct values | | Reference count **increment** | yes | taking a new reference publishes nothing | | Reference count **decrement** that may destroy | no | the deleting thread must see every other owner's writes | | "N items done, results are ready" flag | no | a reader infers other data from the value | The reference-count rows are not theory: libc++'s `shared_ptr` control block increments its count with a relaxed atomic add and decrements it with `acq_rel`, so the thread that drops the last owner sees everything the other owners wrote before it destroys the object. ## Reading the total A statistics counter is usually read either approximately while the program runs (a relaxed load is fine for a dashboard) or exactly at the end. The exact read is safe after `std::thread::join()`: the standard says the completion of the thread synchronises with the successful return of `join()`, so every increment that thread made is visible to the joining thread, whatever order the increments used. ## The cost you actually save 1. On x86-64, clang at `-O2` compiles both `fetch_add(1)` and `fetch_add(1, std::memory_order_relaxed)` to `lock incl` — the instruction is the same, because every locked read-modify-write on x86 is already fully ordered. 2. On arm64 the relaxed form compiles to `ldadd` and the seq_cst form to `ldaddal`, which carries acquire and release semantics. 3. On any target, relaxed lets the compiler move surrounding ordinary loads and stores across the increment, which a seq_cst operation forbids. So relaxed rarely rescues a hot counter on x86-64 — contention on the counter's cache line costs far more than the ordering, and that is a design problem covered with atomic counters in general. Choose relaxed because it states the intent ("only the number matters"), and keep the default wherever you are not sure. ## The failure mode The classic bug is a relaxed counter used as a signal: workers write results into an array and then `done.fetch_add(1, relaxed)`, and the main thread spins until `done == workers` and reads the array. Nothing orders the array writes before the count, so the reads race with the writes — a data race, undefined behavior. The fix is a `release` increment paired with an `acquire` load, or simply `join()` before reading.
- Can two threads see two relaxed counters change in different orders?Yes. Relaxed operations give each atomic object its own coherent modification order, but impose no order across different objects. If thread A increments `drops` and then `mixes`, thread B may observe the new `mixes` before the new `drops`. Any invariant spanning both counters needs release/acquire ordering, seq_cst, or a mutex.
- Is a relaxed fetch_add on a std::atomic<std::uint64_t> safe on a 32-bit target?It is always correct: the standard requires the operation to be atomic whatever the target. What changes is the cost — if `std::atomic<std::uint64_t>::is_always_lock_free` is false there, the library may implement it with a lock, which matters in signal handlers and on hot paths. Check the constant, or `static_assert` it, rather than assume.
- Relaxed increments can be lost, so a relaxed counter undercounts.
- A relaxed load can see the counter go backwards.
- A relaxed counter reaching N proves the workers' other writes are visible.
- Relaxed is always faster, so it should be the default everywhere.
- Relaxed means the operation is no longer atomic, only cheaper.