Struct Packing, Alignment & False Sharing Prevention
CPU Cache Architecture & Cache Lines
Modern x86 and ARM processors fetch memory from L3/L2 cache into L1 cache in 64-byte chunks called cache lines. Poor struct packing creates padding waste, and multiple threads writing to adjacent fields in the same cache line trigger false sharing, destroying multi-core scalability.
Field Reordering & Struct Layout
By default, Rust uses repr(Rust), which automatically reorders fields to minimize alignment padding. However, for deterministic hardware or FFI, you must specify representations:
// 1. FFI & Network Packets: Strict C ABI ordering
#[repr(C)]
pub struct EthernetHeader {
pub dst_mac: [u8; 6],
pub src_mac: [u8; 6],
pub ethertype: u16,
}
// 2. High-Concurrency Multithreading: Prevent False Sharing
#[repr(align(64))]
pub struct PaddedAtomicCursor {
pub value: std::sync::atomic::AtomicU64,
// Compiler guarantees this struct occupies a dedicated 64-byte cache line!
}
Measuring the Penalty of False Sharing
When two CPU cores simultaneously modify atomic variables residing on the same 64-byte cache line, the MESI (Modified, Exclusive, Shared, Invalid) cache coherence protocol forces constant cache line invalidation across the interconnect bus. Padded cursors eliminate this contention, unlocking up to 8x higher atomic throughput on 64-core server nodes.
Inspect struct field padding and enforce 64-byte L1 cache line alignment to prevent false sharing.