多线程伪共享(false sharing)问题分析

#include<stdio.h> 
#include<omp.h> 
#include<string.h> 
#include<time.h>
#include<stdlib.h>
#include<iostream>
using namespace std;



#define NMAX 4096 * 10 
#define NUM_CORE 4 

int g_iBuff[NMAX];


int main()
{
    int alignPos = 0;
    for (int i = 0; i < 65; ++i)
    {
        int * addr = &g_iBuff[i];
        char buf[32];
        int int_addr = atoi(buf);
        if ( int_addr % 64 == 0)
        {
            alignPos = i;
            cout<<"alignPos:"<<int_addr<<endl;
            break;
        }
    }

    for (int pos = 1; pos <= 4096; pos <<= 1)
    {
        memset(g_iBuff, 0 , sizeof(g_iBuff));
        time_t beg = time(0);
#pragma omp parallel for num_threads(NUM_CORE) 
        for (int i = 0; i < NUM_CORE; ++i)
        {
            int tp = i * pos + alignPos;
            for (int j = 0; j < 999999999; ++j)
            {
                g_iBuff[tp]++;
            }
        }
        time_t end = time(0);

        cout << "false shareing: step = "<<pos<<" time = "<< end - beg << "s" <<endl;
    }

    return 0;
}


# g++ XX.cpp -o xx -fopenmp

# ./xx 

我们首先来看一下这段代码的输出结果:

false shareing: step = 1 time = 12s
false shareing: step = 2 time = 13s
false shareing: step = 4 time = 13s
false shareing: step = 8 time = 6s
false shareing: step = 16 time = 3s
false shareing: step = 32 time = 3s
false shareing: step = 64 time = 3s
false shareing: step = 128 time = 3s
false shareing: step = 256 time = 3s
false shareing: step = 512 time = 3s
false shareing: step = 1024 time = 3s
false shareing: step = 2048 time = 3s
false shareing: step = 4096 time = 3s


接下来我们来分析一个程序:


上面这段代码的功能是找到地址是64倍数的内存位置, alignPos;

r接下来我们在4核的机器来来验证伪共享对程序的影响。

当 step = 1时,4个线程写入的位置(相对alignPos开始位置)0,4,8和12,显然存在伪共享。

当 step = 2时,写入的位置分别为0,8,16和24,同样也是伪共享

当 step = 4时,写入的位置分别为0,16,32和48,同样也是伪共享

当 step = 8时,写入的位置分别为0,32,64和96,由于cache是64B对齐,因此,0和32以及64和96存在伪共享,但是比前3种情况要好。

对 step = 16时,写的位置分别为0,64,128,和192,刚好完全不再具有伪共享的问题。

step > 16, 也不会再存在伪共享。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值