False Sharing问题

在多处理器,多线程情况下,如果两个线程分别运行在不同的CPU上,而其中某个线程修改了cache line中的元素,由于cache一致性的原因,另一个线程的cache line被宣告无效,在下一次访问时会出现一次cache line miss,哪怕该线程根本无效改动的这个元素,因此出现了False Sharing问题【1】。

如下图所示,thread1修改了memory灰化区域的第[2]个元素,而Thread0只需要读取灰化区域的第[1]个元素,由于这段memory被载入了各自CPU的硬件cache中,虽然在memory的角度这两种的访问时隔离的,但是由于错误的紧凑地放在了一起,而导致了,thread1的修改,在cache一致性的要求下,宣告了运行Thread0的CPU0的cache line非法,从而出现了一次miss,导致从小从memory中读取到cache line中,而一致性的代价付出了,但结果并不是thread0所care的,导致了效率的降低。关于实验可以参考[2]。

 

因此在多核编程情况下,要特别注意False Sharing问题。

解决的方法可以是:详细参见【1】

__declspec (align(64)) int thread1_global_variable;
__declspec (align(64)) int thread2_global_variable;

或者是

  1. struct ThreadParams 
  2.   // For the following 4 variables: 4*4 = 16 bytes 
  3.   unsigned long thread_id; 
  4.   unsigned long v; // Frequent read/write access variable 
  5.   unsigned long start; 
  6.   unsigned long end; 
  7.  
  8.   // expand to 64 bytes to avoid false-sharing  
  9.   // (4 unsigned long variables + 12 padding)*4 = 64 
  10.   int padding[12]; 
  11. }; 
  12.  
  13. __declspec (align(64)) struct ThreadParams Array[10]; 

 

 

 

【1】http://software.intel.com/en-us/articles/avoiding-and-identifying-false-sharing-among-threads/

【2】http://www.codeproject.com/KB/threads/FalseSharing.aspx

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值