download

Why do two threads updating separate counters slow each other down?

Systems~12 minReviewed 3 Dec 2026Free · No sign-in

Question

A multi-core profiler counts hits from two worker threads in one Counters struct. Thread 1 increments a and thread 2 increments b, 10 million times each. Neither thread touches the other field, yet running both threads together is slower than running them one by one.

  1. Why do two separate AtomicU64 fields contend on a multi-core CPU?
  2. What are the byte offsets of a and b in Counters, and what happens in L1 cache?
  3. Fix Counters with #[repr(C, align(64))] so each counter sits on its own 64-byte cache line.
"CODE · RUST"
use std::sync::atomic::{AtomicU64, Ordering};

#[repr(C)]
struct Counters {
    a: AtomicU64,
    b: AtomicU64,
}
Show hints (3)
  1. "CACHE LINE GRANULARITY"

    CPU cores do not transfer single 8-byte fields between L1 caches. How big is one cache line on x86-64?

  2. "CHECK FIELD OFFSETS"

    In Counters, a sits at byte offset 0 and b sits at offset 8. Both fall inside the first 64 bytes.

  3. "PAD EACH FIELD"

    Wrap AtomicU64 in a #[repr(C, align(64))] newtype so b starts at byte offset 64, or accumulate in a local u64 per thread.

Show checked explanation

Both 8-byte fields sit on the same 64-byte L1 cache line (a at offset 0, b at offset 8). Under MESI cache coherency, every write steals exclusive ownership of that whole line from the other core. That ping-pong traffic is false sharing. Fix it by aligning each counter to 64 bytes (#[repr(C, align(64))]) or accumulating locally and merging once.

"SOLUTION · RUST"
use std::mem::{align_of, offset_of, size_of};
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
use std::thread;
#[repr(C, align(64))]
struct Padded(AtomicU64);
#[repr(C)]
struct Counters { a: Padded, b: Padded }

fn main() {
    let c = Counters { a: Padded(0.into()), b: Padded(0.into()) };
    thread::scope(|s| {
        s.spawn(|| for _ in 0..10_000 { c.a.0.fetch_add(1, Relaxed); });
        s.spawn(|| for _ in 0..10_000 { c.b.0.fetch_add(1, Relaxed); });
    });
    let (a, b) = (c.a.0.load(Relaxed), c.b.0.load(Relaxed));
    println!("size={} align={} off_b={} sums={},{}",
        size_of::<Counters>(), align_of::<Counters>(),
        offset_of!(Counters, b), a, b);
}
"OUTPUT"
size=128 align=64 off_b=64 sums=10000,10000

Compiled and ran the Rust solution, packed vs padded layout checks, and thread-local merge alternative with rustc 1.94.1 on Windows x64. Checked by an editor other than the author.

Walkthrough

There is no logical data race here. Thread 1 only writes a, and thread 2 only writes b. The slowdown comes from hardware cache granularity.

CPU cores fetch and track memory in 64-byte cache lines on x86-64, not in 8-byte words. In the packed Counters struct, a occupies bytes 0..8 and b occupies bytes 8..16. Both fields live on the same 64-byte line.

Under the MESI coherency protocol, a core must hold exclusive ownership of a cache line before writing. Writing invalidates other cores' copies and marks the local line Modified. When core 1 runs a.fetch_add(1), core 2's copy of the whole 64-byte line becomes Invalid. Moments later, core 2 runs b.fetch_add(1) and claims ownership back, invalidating core 1. The line bounces back and forth across cores on every iteration. That hardware contention on unrelated variables is false sharing.

layoutsize_ofalign_ofoffset_of!(b)L1 line sharing
Packed Counters16 B8 B8 Ba and b share one 64 B line
#[repr(C, align(64))] wrapper128 B64 B64 Ba and b occupy separate lines
Thread-local u64 + join merge8 B stack8 BN/AZero shared writes in hot loop

Wrapping each AtomicU64 in #[repr(C, align(64))] struct Padded(AtomicU64) pads each counter to 64 bytes. Now a starts at offset 0, b starts at offset 64, and total struct size is 128 bytes. Each core keeps its own cache line in the Modified state without invalidating the other.

For pure counters, keeping a plain stack u64 per worker and calling fetch_add once before joining is even faster. It removes 9,999,999 atomic operations per thread alongside false sharing.

Common mistakes

  • Expecting Ordering::Relaxed to stop false sharing. Memory ordering relaxes reordering rules, not cache coherency; the shared 64-byte line still bounces across cores on every write.
  • Putting #[repr(align(64))] on Counters instead of on each field wrapper. Aligning the outer struct keeps a at offset 0 and b at offset 8 on the same line.
  • Assuming 64 bytes fits every CPU. Apple Silicon and some ARM64 servers use 128-byte cache lines or prefetch pairs, so libraries like crossbeam_utils::CachePadded align to 128 bytes there.
  • Padding structs on cold paths. Growing a 16-byte struct to 128 bytes multiplies RAM usage by 8x and evicts useful data from L1 and L2 caches.

Follow-up questions

  • "Can you fix the slowdown without padding the struct at all?" Yes. Count hits in a plain local u64 inside each worker thread, then add the local total to the shared atomic once before joining. That replaces 10 million shared atomic writes per thread with one.
  • "How do you confirm false sharing on a live Linux box?" Run perf c2c record and perf c2c report to find hot cache lines with high HITM (hit in modified cache) counts. You can also compare perf stat L1 and LLC cache misses for one thread versus two.
  • "Does false sharing occur if both threads only read a and b?" No. Under MESI, multiple cores hold the same read-only cache line in the Shared state at the same time. Contention starts only when at least one core writes to that line.

What a strong answer covers

Identifies offsets 0 and 8 sharing one 64-byte L1 line, explains MESI invalidation ping-pong as false sharing, pads each field with #[repr(C, align(64))], and notes thread-local accumulation.

Open in interactive practice deck →

Original OfferVibe question. Rust Reference: Alignment modifiers · std::mem::offset_of · std::sync::atomic::AtomicU64.
© 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.