Memory barrier,

memory barrier , also known as a  membarmemory 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;
One might expect the print statement to always print the number "42"; however, if processor #2's store operation were to be performed out of order, then f might be updated before x, and the print statement might therefore print "0" .
Similarly, the load operation for processor #1 could be executed out of order and x could be read before f was checked, so the print statement could again print an unexpected value. Both cases are acceptable for most programs.
A memory barrier can be inserted before processor #2 is assigned to f to ensure that the new value of x is visible to other processors when or before the value of f changes. Another can be inserted before processor #1's access to x to ensure that the value of x is not read until it sees a change in the value of f.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324519812&siteId=291194637