Why does a shared counter lose updates across threads?
Question
Four worker threads each add 50,000 requests to a shared counter. You expect 200000, yet runs often print numbers like 118420.
- Why does this snippet lose updates even though
hitsis anAtomicUsize? - Fix the increment so it always prints
200000without a mutex. - When should you switch from an atomic to a
Mutex?
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
use std::thread;
fn main() {
let hits = AtomicUsize::new(0);
thread::scope(|s| {
for _ in 0..4 {
s.spawn(|| {
for _ in 0..50_000 {
let v = hits.load(Relaxed);
hits.store(v + 1, Relaxed);
}
});
}
});
println!("{}", hits.load(Relaxed));
}Show hints (3)
- "TWO SEPARATE STEPS"
The
loadis atomic and thestoreis atomic, but the gap between them is not. Trace two threads reading10at once. - "ONE INDIVISIBLE STEP"
Look for an
AtomicUsizemethod that reads, adds, and writes back as a single hardware read-modify-write operation. - "TWO LINKED FIELDS"
An atomic handles one word at a time. What if you must update both
countandtotal_bytestogether?
Show checked explanation
Calling load and then store(v + 1) splits one increment into two separate steps, so two threads can read the same value and overwrite each other's update. Replace both lines with hits.fetch_add(1, Relaxed) for a single atomic read-modify-write. Use a Mutex when multiple fields must update together.
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
use std::thread;
fn main() {
let hits = AtomicUsize::new(0);
thread::scope(|s| {
for _ in 0..4 {
s.spawn(|| {
for _ in 0..50_000 {
hits.fetch_add(1, Relaxed);
}
});
}
});
println!("{}", hits.load(Relaxed));
}200000
Compiled and ran the split load-store race, deterministic barrier interleaving, fetch_add fix, and Mutex pair with rustc 1.94.1 on Windows x64. Checked by an editor other than the author.
Walkthrough
Each individual load and store is atomic, so neither tears bytes or triggers undefined behavior. The bug is that the read-modify-write cycle is split across two calls. Two threads can interleave right in the middle:
| step | thread 1 | thread 2 | hits in RAM |
|---|---|---|---|
| 1 | load() returns 10 | 10 | |
| 2 | load() returns 10 | 10 | |
| 3 | store(11) | 11 | |
| 4 | store(11) | 11 (one update lost) |
In C or C++, doing hits++ on a plain shared int is even worse: unsynchronized concurrent writes are a data race and undefined behavior. Safe Rust refuses to share a mutable plain integer across threads at compile time.
hits.fetch_add(1, Relaxed) compiles down to one atomic CPU instruction (such as lock xadd on x86-64). No other thread can slip between the read and write, so 4 threads times 50,000 increments always produces 200000. Relaxed is enough here because hits is a standalone counter and does not publish other memory.
Atomic versus Mutex: an atomic stays lock-free and avoids OS thread parking, making it ideal for one counter or flag. Once two fields must change together (say count and sum for a consistent average), two separate atomics still let a reader see half an update. Wrap both fields in one Mutex<Stats> instead.
Common mistakes
- Assuming an atomic variable makes compound expressions like
load+storeatomic. Only a single read-modify-write method (fetch_add,compare_exchange) is indivisible. - Thinking
volatilein C or C++ fixes a shared counter.volatileprevents compiler caching for hardware I/O; it does not make read-modify-write atomic across cores. - Protecting two linked counters with two separate
AtomicUsizevalues. Another thread can read the newcountpaired with the oldsum. - Wrapping a hot single counter in a global
Mutexunder high contention. Threads queue and block in the kernel whenfetch_addor per-thread counters scale much better.
Follow-up questions
- "Why is
Ordering::Relaxedsafe forfetch_addhere?" Becausethread::scopejoins every worker beforemainprints the final total. Joining synchronizes with each worker's exit, andfetch_addguarantees no increment is lost. - "Even with
fetch_add, 64 cores hammering one counter gets slow. Why, and how do you fix it?" Cache-line bouncing: everyfetch_addneeds exclusive ownership of that 64-byte cache line, stalling cores. Give each thread its own cache-line-padded local counter and sum them when reading. - "What is the difference between a data race and a race condition?" A data race is concurrent conflicting access to the same memory without synchronization (undefined behavior in C, C++, and
unsafeRust). A race condition is any bug where outcome depends on timing, like our split atomicload/store.
What a strong answer covers
Traces the two-thread lost-update interleaving, switches to fetch_add as a single hardware RMW, distinguishes data races from race conditions, and knows when a Mutex is required.
Open in interactive practice deck →