download

Why does a shared counter lose updates across threads?

Systems~10 minReviewed 2 Dec 2026Free · No sign-in

Question

Four worker threads each add 50,000 requests to a shared counter. You expect 200000, yet runs often print numbers like 118420.

  1. Why does this snippet lose updates even though hits is an AtomicUsize?
  2. Fix the increment so it always prints 200000 without a mutex.
  3. When should you switch from an atomic to a Mutex?
"CODE · RUST"
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)
  1. "TWO SEPARATE STEPS"

    The load is atomic and the store is atomic, but the gap between them is not. Trace two threads reading 10 at once.

  2. "ONE INDIVISIBLE STEP"

    Look for an AtomicUsize method that reads, adds, and writes back as a single hardware read-modify-write operation.

  3. "TWO LINKED FIELDS"

    An atomic handles one word at a time. What if you must update both count and total_bytes together?

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.

"SOLUTION · RUST"
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));
}
"OUTPUT"
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:

stepthread 1thread 2hits in RAM
1load() returns 1010
2load() returns 1010
3store(11)11
4store(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 + store atomic. Only a single read-modify-write method (fetch_add, compare_exchange) is indivisible.
  • Thinking volatile in C or C++ fixes a shared counter. volatile prevents compiler caching for hardware I/O; it does not make read-modify-write atomic across cores.
  • Protecting two linked counters with two separate AtomicUsize values. Another thread can read the new count paired with the old sum.
  • Wrapping a hot single counter in a global Mutex under high contention. Threads queue and block in the kernel when fetch_add or per-thread counters scale much better.

Follow-up questions

  • "Why is Ordering::Relaxed safe for fetch_add here?" Because thread::scope joins every worker before main prints the final total. Joining synchronizes with each worker's exit, and fetch_add guarantees 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: every fetch_add needs 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 unsafe Rust). A race condition is any bug where outcome depends on timing, like our split atomic load/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 →

Original OfferVibe question. std::sync::atomic::AtomicUsize · The Rustonomicon: Atomics.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.