Memory Barriers in Modern CPUs
Memory barriers (also called fences ) exist because CPUs and compilers reorder memory operations for performance, and in multi-core systems this reordering can become visible to other cores in surprising ways. Barriers are instructions that restrict this reordering across a specific point in the instruction stream. 1. Why reordering happens Modern CPUs use several tricks that can change the order in which memory operations appear to complete from another core's perspective: Store buffers: a core writes to a local buffer immediately and drains it to cache/memory later, so a store can be delayed relative to later instructions. Out-of-order execution: independent instructions execute in whatever order resources allow. Speculative loads: loads may execute early, before it's certain they should have. Cache coherence protocol delays: invalidations/updates from other cores don't arrive instantane...