In Rust, why is `Ordering::Relaxed` enough for a shared `AtomicUsize` request counter, and is the total read after `join` exact?
answer
- atomicity is not ordering
- one modification order per atomic
- join creates happens-before
- load then store loses updates
basics
~20 sRelaxed still makes each fetch_add one indivisible read-modify-write, so no increment is lost; it only drops ordering with other memory. JoinHandle::join makes every thread operation happen-before it returns, so the total read after joining is exact.
solid answer
~40 sAn `Ordering` controls how an atomic operation orders *other* memory accesses, not whether the operation itself is atomic. With `Relaxed`, each `fetch_add(1, Ordering::Relaxed)` is still a single indivisible read-modify-write on one value, and all threads agree on one modification order for that atomic, so four threads doing 100,000 increments always produce 400,000. What `Relaxed` gives up is any guarantee about other variables, which a counter does not need. The final read is exact because `JoinHandle::join` documents that the thread's completion synchronizes with `join` returning: everything the thread did happens-before the code after `join`. The real bug is splitting the increment into `load` and `store` — each step is atomic, but another thread can write in between, so updates vanish.
code
rust · 25 linesuse std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
fn main() {
let hits = Arc::new(AtomicUsize::new(0));
let lossy = Arc::new(AtomicUsize::new(0));
let handles: Vec<_> = (0..4)
.map(|_| {
let (hits, lossy) = (Arc::clone(&hits), Arc::clone(&lossy));
thread::spawn(move || {
for _ in 0..100_000 {
hits.fetch_add(1, Ordering::Relaxed); // one atomic read-modify-write
let n = lossy.load(Ordering::Relaxed); // two separate atomic operations:
lossy.store(n + 1, Ordering::Relaxed); // another thread can write in between
}
})
})
.collect();
for h in handles {
h.join().unwrap(); // the thread's completion happens-before join returns
}
println!("hits = {}", hits.load(Ordering::Relaxed)); // always 400000
println!("lossy = {}", lossy.load(Ordering::Relaxed)); // usually less
}go deeper
Recall that fetch_add with Relaxed never loses increments and that reading after join gives the final total.
Explain atomicity versus ordering, the single modification order of one atomic, and why JoinHandle::join makes the final Relaxed load exact.
Spot the load-then-store lost update in review, say why it is a logic bug rather than undefined behaviour, and name the moment a counter turns into a signal that needs Release and Acquire.
Weigh a single shared counter against per-thread counters merged later when cache-line contention, not ordering, dominates the cost.
## Two different guarantees People often treat the `Ordering` argument as a dial for "how atomic" an operation is. It is not. Every operation on `AtomicUsize` is atomic whatever ordering you pass. The ordering answers a different question: **what does this operation promise about the other memory accesses around it?** - **Atomicity**: a `fetch_add` reads, adds and writes as one indivisible step. No other thread can slip a write into the middle. - **Modification order**: every atomic variable has one total order of all writes to it, and every thread observes writes to that one variable consistently with that order. - **Ordering of other memory**: whether writes to *other* locations made before this operation are visible to a thread that observes it. This is what `Release`, `Acquire`, `AcqRel` and `SeqCst` add, and what `Relaxed` omits. The Rustonomicon puts it directly: relaxed operations "are still atomic", and a counter "can be safely done by multiple threads using a relaxed fetch_add if you're not using the counter to synchronize any other accesses". ## Why a counter needs nothing more A request counter's whole job is the final number. No thread reads the counter and then decides to touch some other data based on it. So the only properties that matter are the first two, and `Relaxed` provides both: 1. No increment can be lost, because each `fetch_add` is indivisible. 2. The counter never goes backwards for an observer, because reads of one atomic follow its modification order. A stronger ordering here would add fences or stronger instructions on weakly ordered CPUs and buy nothing. ## Why the read after `join` is exact A `Relaxed` load in the middle of the run may see any value the counter has passed through so far — a monitoring thread can read a number that is slightly behind. The read after joining is different. The documentation of `JoinHandle::join` says that "the completion of the associated thread synchronizes with this function returning", so all operations performed by that thread happen before everything after `join`. Once every worker is joined, every increment happens-before main's `load`, and even a `Relaxed` load must return the final value. The same holds when the threads are started with `thread::scope`: the scope joins them before it returns. ## The bug that looks similar ```rust let n = lossy.load(Ordering::Relaxed); lossy.store(n + 1, Ordering::Relaxed); ``` This compiles, and it is not undefined behaviour — both accesses are atomic, so there is no data race. It is still wrong. Two threads can load the same `n` and both store `n + 1`, and one increment disappears. Changing both orderings to `SeqCst` does not help, because the gap between the two operations is the problem, not their ordering. The fix is one read-modify-write: `fetch_add`, or a `compare_exchange` loop when the update is more than an addition. | Code | Data race (UB)? | Lost updates? | |---|---|---| | `fetch_add(1, Relaxed)` | no | no | | `load` then `store`, any ordering | no | yes | | plain `usize` mutated through `unsafe` from several threads | yes | yes | Safe Rust rules out the last row entirely; it does not rule out the middle one, which is a logic error the type system cannot see. ## When `Relaxed` stops being enough Use a stronger ordering as soon as a reader **acts on** the atomic's value to touch other memory: - a flag that says "the config is built, go read it"; - a pointer that publishes a freshly written struct; - a lock bit that guards a value. In those cases the writer needs `Release` and the reader `Acquire` (or `SeqCst` on both). A counter that only reports a number is not one of them. ## Practical notes - Contention, not ordering, is the cost of a hot shared counter: every core fights over one cache line. Per-thread counters summed at the end avoid that, and the theory of why belongs with general concurrency material. - `fetch_add` wraps on overflow rather than panicking. A byte counter that can pass four billion belongs in an `AtomicU64`, which the docs mark as available only on platforms with 64-bit atomic loads and stores. - Prefer `fetch_add` over `load` plus `store` even in code reviewed as "single-writer": a second writer added later silently reintroduces lost updates.
- A metrics thread reads the counter with `load(Ordering::Relaxed)` every second while workers run. Can it ever see the value go down?No. All writes to one atomic form a single modification order, and reads of that atomic by one thread never move backwards in it. The reader may see a value that is slightly behind the latest increment, but successive reads are non-decreasing. Seeing a recent value promptly is a quality-of-implementation matter, not something `SeqCst` would fix.
- Would `fetch_add(1, Ordering::SeqCst)` make the counter more correct?No. The total is already exact with `Relaxed`. `SeqCst` adds a single global order across all `SeqCst` operations on every atomic, which matters only when correctness depends on how operations on different atomics interleave. On weakly ordered CPUs it can cost extra fences for no benefit to a counter.
- Is the `load` followed by `store` version undefined behaviour?No. Both accesses are atomic, so there is no data race, and the program's behaviour is defined: it simply loses increments. Undefined behaviour from the memory model needs a conflicting non-atomic access that is not ordered by happens-before, which safe Rust cannot express.
- Relaxed increments can be lost under contention, so counters need SeqCst.
- A Relaxed load after joining every thread can still return a stale total.
- A load followed by a store with SeqCst is as safe as fetch_add.
- A Relaxed counter can tell readers that other shared data is ready.
- Losing increments with load and store is undefined behaviour in Rust.