Programming: Memory Barrier

Published:

Memory barrier is an instruction to cause the CPU or compiler to enforce an ordering constraint on memory operations before and after it.

Motivated Example

Most modern CPUs perform out-of-order execution for performance optimization, which is correct for the single-thread execution but faulty in multi-thread execution on shared memory.

// Thread 1:
x = 0;
f = 0;
while (f == 0);
// Memory fence required here
print x;

// Thread 2:
x = 42;
// Memory fence required here
f = 1;

In this example, x might still be 0 because the CPU might reorder x=42 and f=1 since the reordering is correct for thread 2. We need to add a memory fence to enforce the order.

Usages

Linux kernel

Linux provides the following functions to enforce memory barriers:

  • smp_mb(): hardware memory barrier on multi-processor systems.
  • smp_rmb(): read memory barrier.
  • smp_wmb(): write memory barrier.
  • mb(), rmb(), wmb(): memory barriers (on single-processor systems).
  • barrier(): software memory barrier.

Links