内存屏障 Memory barrier
By zieckey
All Right Reserved
内存屏障,可以保证在此之前的代码全部执行完才开始执行在此之后的代码
参考wikipedia的定义:
Memory barrier, also known as membar or memory fence or fence instruction, is a type of and a class of which causes a (CPU) or to enforce an ordering constraint on operations issued before and after the barrier instruction.
一个例子。
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”
阅读(405) | 评论(0) | 转发(0) |