Pthread 未加锁,多线程反而比单线程慢
不来的恩特 2020-05-10 09:06:57 今天在做课程实验时,用蒙特卡洛算法求pai,要求通过使用pthread来提升性能,结果使用了多线程后,运行时间比单线程更长,求求大佬们帮助!
# include <stdio.h>
# include <stdlib.h>
# include <math.h>
# include <time.h>
# include <pthread.h>
long long sum = 100000000;
long long num_circle = 0;
int thread_count;
void * compute(void * rank);
int main(int argc , char * argv[]){
long thread;
pthread_t* thread_handlers;
//读取线程数
thread_count = strtol(argv[1],NULL,10);
// printf("%d\n",thread_count);
//获取线程内存空间
thread_handlers = malloc(thread_count * sizeof(pthread_t));
clock_t start, end;
//开始计时
start = clock();
//初始化随机数种子
srand(time(0));
//创建thread_count个线程
for(thread = 0;thread < thread_count;thread ++){
pthread_create(& thread_handlers[thread], NULL, compute, (void*) thread);
}
//合并thread_count个线程
for(thread = 0;thread < thread_count;thread ++){
pthread_join(thread_handlers[thread],NULL);
}
free(thread_handlers);
//结束计时
end = clock();
//计算用时
double duaration = (double)(end - start)/CLOCKS_PER_SEC;
double pai = num_circle *1.0 / sum *4;
printf("finished in %f seconds\n %f",duaration,pai);
}
void* compute(void* rank){
long my_rank = (long) rank;
int my_start = my_rank * (sum / thread_count);
int my_end = (my_rank + 1) * (sum / thread_count) - 1;
for(int i = my_start;i <= my_end;i ++){
double x = 2.0*rand()/RAND_MAX-1;
double y = 2.0*rand()/RAND_MAX-1;
double distance_squared = sqrt(x * x + y * y);
if(distance_squared <= 1.0){
num_circle ++;
}
}
// printf("%f\n",distanc_squared);
return rank;
}