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;
}
...全文
241 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
冲破迷雾 2021-10-30
  • 打赏
  • 举报
回复

您好,我现在也同样遇到了这个情况,请问您有解决这个问题的方法吗?

20,808

社区成员

发帖
与我相关
我的任务
社区描述
Hadoop生态大数据交流社区,致力于有Hadoop,hive,Spark,Hbase,Flink,ClickHouse,Kafka,数据仓库,大数据集群运维技术分享和交流等。致力于收集优质的博客
社区管理员
  • 分布式计算/Hadoop社区
  • 涤生大数据
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧