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

#include 
#include 
#include 
#include
#include
#include
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:"<


# 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, 也不会再存在伪共享。



你可能感兴趣的:(C++)