内存屏障 memory barrier
by zieckey
all right reserved
内存屏障,可以保证在此之前的代码全部执行完才开始执行在此之后的代码
参考wikipedia的定义:
memory barrier, also known as membar or memory fence or fence instruction, is a type of barrier and a class of instruction which causes a central processing unit (cpu) or compiler to enforce an ordering constraint on memory operations issued before and after the barrier instruction.
http://en.wikipedia.org/wiki/memory_barrier
一个例子。
processor #1:
x = f = 0
loop:
load the value in location f, if it is 0 goto loop
print the value in location x
processor #2:
store the value 42 into location x
store the value 1 into location f
上面的例子中,变量 x f 初始化值都是0。我们期望输出“42”。但是结果并不总是这样。
如果 processor #2 的执行顺序是乱序的,也就是说,对f赋值的语句先于对x赋值的语句,那么就有可能输出“0”
对于大多数的程序来说,这种特例情况是不能容忍的。
如果将内存屏障置于对f赋值的语句之前,那么就能保证 processor #2 先对x赋值,然后才对f赋值。这样就能得到我们期望的结果,输出“42”