A memory barrier , also known as a membar , memory fence or fence instruction , is a barrier instruction that causes the central processing unit (CPU) or compiler to enforce ordering constraints on memory operations issued before and after the barrier instruction. This usually means that operations issued before the barrier are guaranteed to be executed before operations issued after the barrier.
When a program is run on a single-CPU computer, the hardware performs the necessary bookkeeping to ensure that the program executes as if all memory operations were performed in the order specified by the programmer (program order), so no memory barriers are required. However, when memory is shared with multiple devices, such as other CPUs in a multiprocessor system or memory-mapped peripherals, out-of-order accesses can affect program behavior. For example, the second CPU can see memory changes made by the first CPU in a different sequence than the program order.
The following two processor programs give an example of how this out-of-order execution affects program behavior: Initially, both memory locations x and f hold the value 0. The program running on processor #1 loops when f is zero, then prints the value of x. The program running on processor #2 stores the value 42 into x, and then stores the value 1 into f. The pseudocode for these two program fragments is shown below. The steps of the program correspond to individual processor instructions.
Processor #1:
while (f == 0); // Memory fence required here print x;
Processor #2:
x = 42; // Memory fence required here f = 1;