Why do two threads updating separate counters slow each other down?
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.
- Why do two separate
AtomicU64fields contend on a multi-core CPU? - What are the byte offsets of
aandbinCounters, and what happens in L1 cache? - Fix
Counterswith#[repr(C, align(64))]so each counter sits on its own 64-byte cache line.
use std::sync::atomic::{AtomicU64, Ordering};
#[repr(C)]
struct Counters {
a: AtomicU64,
b: AtomicU64,
}Show hints (3)
- "CACHE LINE GRANULARITY"
CPU cores do not transfer single 8-byte fields between L1 caches. How big is one cache line on x86-64?
- "CHECK FIELD OFFSETS"
In
Counters,asits at byte offset0andbsits at offset8. Both fall inside the first 64 bytes. - "PAD EACH FIELD"
Wrap
AtomicU64in a#[repr(C, align(64))]newtype sobstarts at byte offset64, or accumulate in a localu64per 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.
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);
}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.
| layout | size_of | align_of | offset_of!(b) | L1 line sharing |
|---|---|---|---|---|
Packed Counters | 16 B | 8 B | 8 B | a and b share one 64 B line |
#[repr(C, align(64))] wrapper | 128 B | 64 B | 64 B | a and b occupy separate lines |
Thread-local u64 + join merge | 8 B stack | 8 B | N/A | Zero 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::Relaxedto 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))]onCountersinstead of on each field wrapper. Aligning the outer struct keepsaat offset0andbat offset8on 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::CachePaddedalign 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
u64inside 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 recordandperf c2c reportto find hot cache lines with high HITM (hit in modified cache) counts. You can also compareperf statL1 and LLC cache misses for one thread versus two. - "Does false sharing occur if both threads only read
aandb?" 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 →