← [ ABORT TO HUD ]
SEQ. 1
SEQ. 2

Struct Packing, Alignment & False Sharing Prevention

📐 Memory Layout, Struct Packing & Cache Locality15 min120 BASE XP⌨ HANDS-ON LAB

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.

⌨ HANDS-ON LABInspect Struct Layout & False Sharing Alignment
⭐ +150 XP

Inspect struct field padding and enforce 64-byte L1 cache line alignment to prevent false sharing.

1Check struct field alignment and layout padding using cargo check.
2Run benchmark measuring atomic throughput with 64-byte cache-line isolation.
lab-sandbox — simulated environment
INFINITY LAB SANDBOX v2.6 — simulated shell
Type the command for the current objective. Helpers: "hint", "solution", "clear".
$
OBJECTIVE 1 / 2 — type "hint" if stuck
SYNAPSE VERIFICATION
QUERY 1 // 1
What causes 'false sharing' in multi-threaded CPU architectures?
Two threads on different cores writing to independent variables that reside within the same 64-byte cache line
A single thread attempting to lock two mutexes simultaneously in reverse order
A GPU thread writing to host memory without calling cudaStreamSynchronize
The compiler reordering non-atomic load instructions across an acquire fence