Overview
Modern CPUs and compilers often reorder memory reads and writes to improve performance. While this is fine for a single thread, it can cause bugs in multi-threaded code where one thread expects to see another thread's writes in a specific order.
Function
A memory barrier (or fence) ensures that all memory operations before the barrier are completed before any operations after the barrier are allowed to start.
Types
- Load Barrier: Ensures previous loads are finished.
- Store Barrier: Ensures previous stores are visible to other cores.
- Full Barrier: Enforces both load and store ordering.