Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4201125
  • 博文数量: 176
  • 博客积分: 10059
  • 博客等级: 上将
  • 技术积分: 4681
  • 用 户 组: 普通用户
  • 注册时间: 2006-03-24 12:27
文章分类

全部博文(176)

文章存档

2012年(1)

2011年(4)

2010年(14)

2009年(71)

2008年(103)

分类: C/C++

2011-03-17 16:39:02

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