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

本文通过一个具体的C++ OpenMP程序示例,演示了伪共享如何影响多线程程序的运行效率,并通过实验展示了不同内存对齐设置下程序运行时间的变化。
#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, 也不会再存在伪共享。



### C++ 实现跳动的粒子爱心动画 以下是基于用户需求设计的个完整的动态粒子爱心程序代码。该代码通过控制台输出实现了个不断变化大小的心形图案,并模拟了心跳的效果。 #### 主要思路 利用参数化方程绘制心形曲线,调整时间间隔来实现动态效果。具体来说,使用极坐标系下的心形方程 `r(θ)` 来计算点的位置并打印到屏幕上[^1]。为了增加复杂性和真实感,可以加入随机噪声或粒子运动轨迹[^2]。 ```cpp #include <iostream> #include <cmath> #include <thread> #include <vector> using namespace std; // 定义屏幕尺寸和比例因子 const int WIDTH = 80; const int HEIGHT = 25; const double SCALE_FACTOR = 2.0; void clearScreen() { cout << "\033[2J\033[1;1H"; // ANSI 清屏命令 } pair<double, double> heart(double t, double scale) { const double a = 1.0 * scale; // 控制整体大小的比例系数 double r = pow(sin(t), 3); // 极径部分 double x = a * 16 * sin(t)*sin(t)*cos(t); double y = -a * (13*cos(t)-5*cos(2*t)-2*cos(3*t)-cos(4*t)); return make_pair(x / SCALE_FACTOR, y / SCALE_FACTOR); } int main() { vector<pair<int, int>> points; bool running = true; while(running){ clearScreen(); // 计算当前帧的所有像素位置 points.clear(); for(int i=0;i<720;i++){ pair<double,double> p = heart(i*M_PI/360.0, 1 + abs(cos(M_PI*clock()/CLOCKS_PER_SEC))); // 动态缩放 int px = round(WIDTH/2 + p.first); int py = round(HEIGHT/2 - p.second); if(px >=0 && px <WIDTH && py>=0 && py<HEIGHT ){ points.emplace_back(px,py); } } // 绘制图像 for(int j=0;j<HEIGHT;j++) { for(int k=0;k<WIDTH;k++) { char c=' '; for(auto &[px,py]:points){ if(j==py && k==px){ c='❤'; break; }else{ // 添加些随机粒子作为装饰 static auto seed = chrono::steady_clock::now().time_since_epoch().count(); default_random_engine generator(seed+j+k+i); uniform_real_distribution<float> distribution(-SCALE_FACTOR,+SCALE_FACTOR); float noiseX=distribution(generator)/2; float noiseY=distribution(generator)/2; if(abs(k-(px+noiseX))<=1 && abs(j-(py+noiseY))<=1){ c='.'; break; } } } cout<<c; } cout<<"\n"; } this_thread::sleep_for(chrono::milliseconds(100)); // 延迟让画面流畅过渡 } } ``` 此代码片段定义了种方法用于生成随时间波动的心型图形,并且加入了少量随机扰动以模仿粒子漂浮现象[^1]^[]^。注意这里采用了ANSI转义序列清除终端内容以便连续更新显示区域[^2].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值