Avoid False Sharing in Rust With crossbeam's CachePadded
Wrap per-thread atomics in crossbeam_utils::CachePadded to keep each on its own cache line in Rust, with size checks, scoped threads and a repr(align) option.

Rust gives you data-race freedom in safe code, and it does nothing about false sharing. Two AtomicU64 values in one struct that different threads update still sit in one cache line and still make the line bounce between cores. The tool the Rust ecosystem settled on is CachePadded<T> from the crossbeam-utils crate, a wrapper that aligns and pads its contents to the length of a cache line. This post shows how to use it for per-thread counters with scoped threads, how to check the layout with size_of and align_of, how its alignment is chosen per architecture, and how to do the same job with #[repr(align)] if you want no dependency. Examples use Rust 1.82 and crossbeam-utils 0.8.
The problem in Rust terms
Here is a vector of atomic counters, one per worker.
use std::sync::atomic::{AtomicU64, Ordering};
fn main() {
let counters: Vec<AtomicU64> = (0..4).map(|_| AtomicU64::new(0)).collect();
println!("size of one counter: {}", std::mem::size_of::<AtomicU64>());
println!("four counters take: {} bytes", 4 * std::mem::size_of::<AtomicU64>());
counters[0].fetch_add(1, Ordering::Relaxed);
}size of one counter: 8
four counters take: 32 bytesEight bytes each, so all four fit in one 64-byte line, and in one 128-byte line too. If four threads each increment their own element, the line ping-pongs among the four cores on every increment. The program is correct and slow, exactly as in the C case from the first false-sharing post in this series.
CachePadded
Add the dependency in Cargo.toml:
[dependencies]
crossbeam-utils = "0.8"CachePadded<T> is a generic wrapper that dereferences to T, so most code changes only in the declaration.
use crossbeam_utils::CachePadded;
use std::sync::atomic::{AtomicU64, Ordering};
fn main() {
let counters: Vec<CachePadded<AtomicU64>> =
(0..4).map(|_| CachePadded::new(AtomicU64::new(0))).collect();
println!("size of CachePadded<AtomicU64>: {}",
std::mem::size_of::<CachePadded<AtomicU64>>());
println!("align of CachePadded<AtomicU64>: {}",
std::mem::align_of::<CachePadded<AtomicU64>>());
counters[0].fetch_add(1, Ordering::Relaxed);
println!("counter 0 = {}", counters[0].load(Ordering::Relaxed));
}size of CachePadded<AtomicU64>: 128
align of CachePadded<AtomicU64>: 128
counter 0 = 1On x86-64 the size and alignment are 128, not 64. The crate's documentation explains the choice: on x86-64, aarch64 and powerpc64 it assumes a 128-byte padding unit, because the adjacent-line prefetcher on many Intel cores pulls in pairs of lines, and because Apple silicon and some Arm cores use 128-byte lines. It uses 32 bytes on arm, mips and a few others, 16 on m68k, 256 on s390x and 64 on everything else. The wrapper is #[repr(align(N))] under the hood, selected by cfg attributes on the target architecture, so the choice is compile-time and follows the target, not the CPU the binary later meets.
The cost is memory. Each counter now takes 128 bytes where it needed 8, so a vector of four takes 512 bytes. For per-thread slots, that is nothing, and for a million objects it is a lot.
A complete example with scoped threads
Here is a program that runs four workers, each incrementing its own padded counter, and then sums them. It uses std::thread::scope, stable since Rust 1.63, so the threads can borrow the vector without Arc.
use crossbeam_utils::CachePadded;
use std::sync::atomic::{AtomicU64, Ordering};
use std::thread;
const WORKERS: usize = 4;
const ITERATIONS: u64 = 5_000_000;
fn main() {
let counters: Vec<CachePadded<AtomicU64>> =
(0..WORKERS).map(|_| CachePadded::new(AtomicU64::new(0))).collect();
thread::scope(|s| {
for id in 0..WORKERS {
let slot = &counters[id];
s.spawn(move || {
for _ in 0..ITERATIONS {
slot.fetch_add(1, Ordering::Relaxed);
}
});
}
});
let total: u64 = counters.iter().map(|c| c.load(Ordering::Relaxed)).sum();
println!("total = {total}");
}total = 20000000let slot = &counters[id] takes a shared reference, which is Send because AtomicU64 is Sync. Each worker updates only its own slot, and with the padding, each slot is on a separate line, so the cores do not invalidate one another. The Relaxed ordering is enough: the counters are independent, and the scope's end synchronises the threads with the main thread before the sum, since thread::scope joins every thread before it returns.
Remove CachePadded and keep everything else, and the same program becomes the false-sharing version. Comparing the two on your hardware, with time or the criterion crate, is the quickest way to see the effect.
Doing it without the dependency
The wrapper is a few lines. If you do not want a crate for it, define one with #[repr(align)].
use std::sync::atomic::AtomicU64;
#[repr(align(128))]
struct Padded<T>(T);
fn main() {
println!("size: {}", std::mem::size_of::<Padded<AtomicU64>>());
println!("align: {}", std::mem::align_of::<Padded<AtomicU64>>());
let p = Padded(AtomicU64::new(7));
println!("inner: {}", p.0.load(std::sync::atomic::Ordering::Relaxed));
}size: 128
align: 128
inner: 7#[repr(align(N))] takes a literal, so you cannot compute the number from a constant, and you pick it by hand. The Rust Reference documents the attribute under type layout, and it requires N to be a power of two. The crate adds three things: the per-architecture constants, the Deref and DerefMut implementations so you can call methods without writing .0, and a tested set of derives. If you use the hand-written version, add Deref yourself, or accept the .0.
Checking the layout in a test
Layout bugs are quiet, so assert them. A unit test that checks no two elements share a line is cheap.
use crossbeam_utils::CachePadded;
use std::sync::atomic::AtomicU64;
#[test]
fn counters_do_not_share_a_line() {
let v: Vec<CachePadded<AtomicU64>> =
(0..4).map(|_| CachePadded::new(AtomicU64::new(0))).collect();
let line = std::mem::align_of::<CachePadded<AtomicU64>>();
for pair in v.windows(2) {
let a = &*pair[0] as *const AtomicU64 as usize;
let b = &*pair[1] as *const AtomicU64 as usize;
assert!(b - a >= line, "adjacent counters closer than {line} bytes");
}
}running 1 test
test counters_do_not_share_a_line ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00sThe test takes the address of the atomic inside each wrapper and requires consecutive addresses to be at least one padding unit apart. If a future change shrinks the padding, or someone replaces CachePadded with a bare atomic, the test fails.
Where Rust code usually needs it
The standard library's channels and crossbeam's queues already pad their internal head and tail indices, so you rarely write that yourself. You need it in your own structures: per-thread statistics arrays, sharded counters, the indices of a ring buffer you write, per-worker state in a thread pool and any Vec of independently updated atomics or locks. A Vec<Mutex<T>> is the least obvious: each Mutex is small, several fit a line, and unrelated locks contend on the line.
It does not fix two threads updating one atomic, which is true sharing. For a hot shared counter, shard it: one padded counter per thread, summed on read, as the post on sharding counters in this series shows.
Padding a struct of several fields
Often a worker has more than one hot field, for example a request count and an error count. Wrap the whole struct, not each field, so the fields of one thread stay together on one padded unit and only different threads' units are separated.
use crossbeam_utils::CachePadded;
use std::sync::atomic::AtomicU64;
struct WorkerStats {
requests: AtomicU64,
errors: AtomicU64,
}
struct Pool {
stats: Vec<CachePadded<WorkerStats>>,
}
fn main() {
let pool = Pool {
stats: (0..4)
.map(|_| CachePadded::new(WorkerStats {
requests: AtomicU64::new(0),
errors: AtomicU64::new(0),
}))
.collect(),
};
println!("workers: {}", pool.stats.len());
println!("bytes per worker: {}", std::mem::size_of::<CachePadded<WorkerStats>>());
}workers: 4
bytes per worker: 128Both counters of a worker, 16 bytes together, share one 128-byte unit, so the worker's own two writes do not cost a coherence transfer, and different workers never touch the same unit. Wrapping each field separately would give 256 bytes per worker for no benefit. The rule is to pad at the boundary of ownership: whatever one thread writes together is one unit.
Read-mostly fields belong elsewhere. A configuration value that every worker reads and nobody writes can sit in an ordinary struct, since reads do not invalidate. Mixing it into the padded unit would only waste space, and putting it next to a hot written field would make every write invalidate every reader's copy. Keep the read-mostly data in its own allocation, or in a padded struct of its own.
Measuring that it helped
Do not trust padding on faith. Write a benchmark with the criterion crate that runs the scoped-thread loop with and without CachePadded, at the thread counts you care about, and compare the timings. On a machine with several cores the unpadded version typically shows time growing as threads are added, while the padded version stays near flat. If you see no difference, the counters were not contended, or the compiler hoisted the increments into a register, which Rust will do for a non-atomic loop and cannot do for fetch_add. For a quick look at contention without a benchmark harness, perf c2c record and perf c2c report work on Rust binaries built with debug symbols, since they report cache lines by address and by source line.


