我的多线程C程序运行以下例程:
#define NUM_LOOP 500000000
long long sum = 0;
void* add_offset(void *n){
int offset = *(int*)n;
for(int i = 0; i<NUM_LOOP; i++) sum += offset;
pthread_exit(NULL);
}
当然sum
应该通过获取锁来更新,但在此之前我对这个简单程序的运行时间有疑问。
当主要功能是(单线程)时:
int main(void){
pthread_t tid1;
int offset1 = 1;
pthread_create(&tid1,NULL,add_offset,&offset1);
pthread_join(tid1,NULL);
printf("sum = %lld\n",sum);
return 0;
}
输出和运行时间为:
sum = 500000000
real 0m0.686s
user 0m0.680s
sys 0m0.000s
当主要功能是(多线程顺序)时:
int main(void){
pthread_t tid1;
int offset1 = 1;
pthread_create(&tid1,NULL,add_offset,&offset1);
pthread_join(tid1,NULL);
pthread_t tid2;
int offset2 = -1;
pthread_create(&tid2,NULL,add_offset,&offset2);
pthread_join(tid2,NULL);
printf("sum = %lld\n",sum);
return 0;
}
输出和运行时间为:
sum = 0
real 0m1.362s
user 0m1.356s
sys 0m0.000s
到目前为止,程序按预期运行。但是当主函数是(Multi Threaded Concurrent)时:
int main(void){
pthread_t tid1;
int offset1 = 1;
pthread_create(&tid1,NULL,add_offset,&offset1);
pthread_t tid2;
int offset2 = -1;
pthread_create(&tid2,NULL,add_offset,&offset2);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
printf("sum = %lld\n",sum);
return 0;
}
输出和运行时间为:
sum = 166845932
real 0m2.087s
user 0m3.876s
sys 0m0.004s
由于缺少同步而导致sum
的错误值不是问题,而是运行时间。并发执行的实际运行时间远远超过顺序执行的运行时间。它与多核CPU中并发执行的期望相反。
请解释这里可能出现的问题。
答案 0 :(得分:3)
如果多个线程访问相同的共享状态(至少在x86上),这不是一种不常见的效果。它通常称为cache line ping-pong:
每当一个核心想要更新该变量的值时,它首先必须从另一个核心获取缓存行的“所有权”(锁定缓存行以进行写入),这需要一些时间。然后另一个核心想要缓存线...
因此,即使没有同步原语,与顺序情况相比,您也需要付出相当大的开销。
答案 1 :(得分:0)
根据@spectras的建议,我对add_offset
例程进行了以下更改:
#define NUM_LOOP 500000000
long long sum = 0;
void* add_offset(void *n){
int offset = *(int*)n;
long long sum_local = sum; //read sum
for(int i = 0; i<NUM_LOOP; i++) sum_local += offset;
sum = sum_local; //write to sum
pthread_exit(NULL);
}
多线程并发执行的主要功能与上面相同,运行时现在正如预期的那样,即:
sum = 500000000
real 0m0.683s
user 0m1.356s
sys 0m0.000s
另一个输出和运行时是:
sum = -500000000
real 0m0.686s
user 0m1.360s
sys 0m0.000s
这两个且只有这两个输出值是预期的,因为线程不同步。输出中sum
的值反映了最后更新sum
的线程(偏移量= 1或偏移量= -1)。