首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[linux][x86]LOCK指令的影响

[linux][x86]LOCK指令的影响

作者头像
皮振伟
发布2018-11-30 11:54:36
2K0
发布2018-11-30 11:54:36
举报
文章被收录于专栏:皮振伟的专栏皮振伟的专栏

前言: 一般多线程并行操作,对个别的变量需要使用原子操作,经常用到__sync_fetch_and_add类似的函数,来避免CPU操作各自的cache没有同步内存而造成的数据数错。 在x86平台上,反汇编__sync_fetch_and_add就可以看到,实际上是lock addq $0x1,(%rax)。 如果多个CPU并行使用__sync_fetch_and_add,会不会造成性能问题呢?LOCK指令的影响范围是多少呢?同一个CORE的两个THREAD,同一个SOCKET的两个CORE,以及两个SOCKET之间呢? 分析: 1,sample code 手写一段代码,两个thread分别可以绑定在两个CPU上,一起跑__sync_fetch_and_add,看看时间上是不是会受到影响。需要注意的是“long padding[100]; // avoid cache false-sharing”这行,加上padding用来避免CPU cache的false-sharing问题。 #include <sched.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <sys/time.h> #include <pthread.h> void bench_atomic(long *l) { long loop; struct timeval start, end; suseconds_t eplased = 0; gettimeofday(&start, NULL); // benchmark for (loop = 0; loop < 0x20000000; loop++) { __sync_fetch_and_add(l, 1); } gettimeofday(&end, NULL); eplased = (end.tv_sec - start.tv_sec)*1000*1000 + end.tv_usec - start.tv_usec; printf("ATOMICC test %ld msec\n", eplased); } void *routine(void *p) { long *l = (long*)p; cpu_set_t my_set; CPU_ZERO(&my_set); CPU_SET(*l, &my_set); sched_setaffinity(0, sizeof(cpu_set_t), &my_set); *l = 0; bench_atomic(l); } int main(int argc, char **argv) { pthread_t p0, p1; long cpu0 = 4; long padding[100]; // avoid cache false-sharing long cpu1 = 8; if (argc != 3) { printf("%s CPU CPU\n", argv[0]); return 0; } cpu0 = atoi(argv[1]); cpu1 = atoi(argv[2]); padding[0] = cpu0; printf("main thread run on CPU %ld, worker thread run on CPU %ld and CPU %ld\n", padding[0], cpu0, cpu1); bench_atomic(&padding[0]); pthread_create(&p0, NULL, routine, &cpu0); pthread_create(&p1, NULL, routine, &cpu1); pthread_join(p0, NULL); pthread_join(p1, NULL); printf("result %ld and CPU %ld\n", cpu0, cpu1); return 0; } 2, cpu topology 使用lscpu判断cpu的分布

测试使用cpu 5&7测试同一个core,5&9测试同一个socket,5&4测试不同的socket。 3, threads in core

单独用main thread跑,和多个CPU hyper thread并行跑,时间上没有差别。 4, cores in socket

同一个socket上的多个core并行跑,没有受到影响。 5, sockets in NUMA

跨NUMA并行跑,没有受到影响。 6, LOCK 查SDM可以确定,目前常用的haswell,broadwell和skylake,LOCK都不会锁内存了,而是锁cache,由cache一致性保证数据一致性。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-10-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 AlwaysGeek 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档