Chinaunix首页 | 论坛 | 博客
  • 博客访问: 20531
  • 博文数量: 13
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 92
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-09 09:42
文章分类

全部博文(13)

文章存档

2014年(13)

我的朋友

分类: LINUX

2014-08-12 11:27:52

多核编程的过程中有两个与memory有关的问题,需要我们注意,否则程序运行的过程中会有逻辑上的错误。

1. Cache coherence,cache一致性的问题。cache一致性是指在多核环境下,如果每个cpu都有自己的cache(通常指l2 cache),对于同一块memory可能被多个核共享,也就是说多个cpu的cache中都有该memory的一块映射,一个cpu对cache内容的更改可以同步的被其他的cpu所发现(也就是说其他cpu cache中的内容会被自动刷新或invalid)。如果硬件支持cache一致性,那么对于共享内存中的数据的操作,软件不需要执行额外的cache同步维护操作;如果硬件不支持cache一致性的维护,那么软件需要维护cache的一致性,在执行完成数据写操作之后,进行相应的cache flush操作,保证其他的核得到数据的更新;读取数据之前,执行cache invalid操作,从memory中取得新的内容。

2. consistency is about ordering, or the system state at a moment in time.  这里的一致性主要和cpu执行的reorder相关,也就说load和store的操作可能在cpu执行的过程中被reorder从而使的c程序中的逻辑关系无法保证。例如:

cpu 0    和 cpu 1共享一段内存进行数据交互,内存中包含两部分的数据:flag和contents. cpu 0填写contents的内容,然后update flag; cpu1 loop flag标志,然后对contents的内容进行计算和处理。对应的伪代码如下:

cpu 0:

memset(&contents, 0xff, sizeof(contents));

flag=1;

cpu 1

while (flag == 1)

    process contents.

在调试包处理程序的时候,就遇到了consistency的问题。cpu 1发现flag被更新了,然后就去处理contents,但是contents的内容不是0xff,而是不确定的值。其中的原因是什么呢?

原因就是cpu不能保证两个写操作按顺序的更新到cpu 1. CPU 1 might see the "write" field get updated before the memset stores are visible there. Only stores to the same cache line will definitely show up in order to the reader, unless you do __insn_mf() to force ordering (which can be slow). 这种错误的出现和cpu的memory consistency models 有关,问题只会出现在relaxed memory model模式的cpu上,在Implicit memory model的cpu上不会存在此类问题。

要解决这种问题,最简单的方式就是在更新完content之后,增加一个memory fence操作,保证contents更新完成后再执行flag的更新操作。

如果contents和flag可以存放在一个cache line中,那么也可以不用mf,而是采用更为高效的模式。

      memset(&contents, 0xff, sizeof(contents));

      // Don't let the flag be written before the content. This compiler

      //  directive is sufficient because the contents and the flag are

     // on the same cache line.  We don't need to do a hardware memory fence.
      __memory_barrier();
    flag = 1;

阅读(867) | 评论(0) | 转发(0) |
0

上一篇:prctl()函数应用

下一篇:用引用返回值

给主人留下些什么吧!~~