多线程伪共享FalseSharing
2024-09-02 16:42:34
1. 伪共享产生:
在SMP架构的系统中,每个CPU核心都有自己的cache,当多个线程在不同的核心上,并且某线程修改了在同一个cache line中的数据时,由于cache一致性原则,其他核心cache中相同cache line会失效,从而产生cache miss,并重新从内存中读入数据到cache line,显然,这样多核心并没有实现真正的共享,称之为伪共享。
如下图:cpu0,cpu1中的Thread0和Thread1访问统一cache line中的不同数据,此时如果Thread1修改了cache line中块1的数据,则cpu0中的cache line同样也会失效,这时当Thread0读取cache line中的块0的数据时,就会产生cache miss,并更新cache line;
2. 测试:
1. 查看cacheline对齐字节数;
cat /proc/cpuinfo cache_alignment :
2. 测试代码:
#include <stdio.h>
#include <pthread.h> #define CACHE_LINE 64 struct num {
//使用attribute设置cacheline对齐
int number __attribute__ ((aligned(CACHE_LINE)));
//或者使用padding对cacheline进行补齐
//char padding[CACHE_LINE-sizeof(int)];
}; struct num arr_num[]; void *thread0(void *params)
{
arr_num[].number = ; for (unsigned int i = ; i < (unsigned int)-; i++) {
arr_num[].number++;
}
} void *thread1(void *params)
{
arr_num[].number = ; for (unsigned int i = ; i < (unsigned int)-; i++) {
arr_num[].number++;
}
} int main()
{
pthread_t tid[]; pthread_create(&tid[], NULL, thread0, NULL);
pthread_create(&tid[], NULL, thread1, NULL); pthread_join(tid[], NULL);
pthread_join(tid[], NULL); return ;
}
测试结果对比:
不使用cacheline对齐或者补齐
wanpengcoderMac-mini:~ Alex$ time ./false_sharing real 0m34.645s
user 1m8.875s
sys 0m0.079s
使用cacheline对齐或者补齐
wanpengcoderMac-mini:~ Alex$ time ./false_sharing real 0m10.193s
user 0m20.236s
sys 0m0.026s
最新文章
- jquery动态合并表格行
- 利用crontab系统每天定时备份MySQL数据库
- 《HelloGitHub月刊》第03期
- JS tab切换事件
- [Shoi2007]Bookcase 书柜的尺寸 dp
- 正则表达式替换img标签src值!!!
- .net中,控件(Name)属性或ID属性的常见命名规则
- Python 2 中的编码
- Python 与 C/C++ 交互的几种方式
- 亚马逊AWS EC2云实例AMI安装LNMP环境(3)——Mysql5.5
- Adobe Flash Player 因过期而遭遇阻止怎么办
- python与redis交互
- 5.2、Android Studio截图
- java并发编程可见性与线程封闭
- 8.docker的安全性
- spring事务详解(二)简单样例
- thinkphp5报错
- std::thread 不 join
- Output assignment statements in the output statement
- Android JNI访问Java成员
热门文章
- ASP.Net MVC+Ibaties架构
- bzoj4760[USACO2017 Jan]Hoof,Paper,Scissors
- 【bzoj2223】[Coci 2009]PATULJCI 主席树
- 【bzoj3524】[Poi2014]Couriers 主席树
- shell脚本学习—条件测试和循环语句
- BZOJ4310 跳蚤(后缀数组+二分答案)
- 求熵 python 代码
- CentOS scp远程拷贝
- [2018集训队作业][UOJ424] count [笛卡尔树+括号序列+折线法+组合数学]
- CentOS 6.5 下安装配置 mysql