Saturday, January 23, 2016

Memory barrier

Memory barrier is a ordering constraint applied to processor on memory instructions, before and after the barrier.
i.e. the instructions before the barrier are guaranteed to be executed before the instruction after the barrier. The out of order execution does not matter in a single processor, but if there are multiple processors, they may employ out of order execute for optimization.

e.g.

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 operations are executed out-of-order, it is possible for f to be updated before x, and the print statement might therefore print "0". Similarly, processor #1's load operations may be executed out-of-order and it is possible for x to be read before f is checked, and again the print statement might therefore print an unexpected value. For most programs neither of these situations are acceptable. A memory barrier can be inserted before processor #2's assignment to f to ensure that the new value of x is visible to other processors at or prior to the change in the value of f. Another can be inserted before processor #1's access to x to ensure the value of x is not read prior to seeing the change in the value of f.

Taken from https://en.wikipedia.org/wiki/Memory_barrier