Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3470746
  • 博文数量: 1805
  • 博客积分: 135
  • 博客等级: 入伍新兵
  • 技术积分: 3345
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-19 20:01
文章分类

全部博文(1805)

文章存档

2017年(19)

2016年(80)

2015年(341)

2014年(438)

2013年(349)

2012年(332)

2011年(248)

分类:

2011-08-03 14:18:24

内存屏障 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”
阅读(391) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~