您的位置:首页 > 其它

一句话解说内存屏障 Memory barrier

2016-06-21 18:30 351 查看
 一句话解说内存屏障 Memory barrier 2011-03-17
16:39:02

分类: C/C++

内存屏障 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”
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: