标题:[求助]多线程概率法求解pi值
只看楼主
ycz815
Rank: 1
等 级:新手上路
帖 子:8
专家分:0
注 册:2006-4-27
 问题点数:0 回复次数:1 
[求助]多线程概率法求解pi值
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 500000
int main(void)
{ int i, sum = 0;
double x, y;
srand(time(NULL));
for(i = 1; i < N; i++)
{ x = (double) rand() / RAND_MAX;
y = (double) rand() / RAND_MAX;
if((x * x + y * y) < 1)
sum++; }
printf("PI = %f\n", (double) 4 * sum / N);
return 0; }
将该程序用多线程实现,我刚开始学习线程,请高手帮忙,最好能把程序写上,谢谢大家了!望大家不吝赐教!!
搜索更多相关主题的帖子: 线程 概率 求解 
2007-04-27 13:50
ycz815
Rank: 1
等 级:新手上路
帖 子:8
专家分:0
注 册:2006-4-27
得分:0 

#include <stdio.h>
#include<stdlib.h>
#include <pthread.h>
#include <time.h>
#define N 500000
#define no_threads 10

int global_index=0;
int sum=0;
pthread_mutex_t mutex1;
void *slave(void *ignored)
{
int local_index,partial_sum=0;
double x,y;
do{
pthread_mutex_lock(&mutex1);
local_index=global_index;
global_index++;
pthread_mutex_unlock(&mutex1);
// sleep(0.00001);
if(local_index<N)
srand(time(NULL));

{x=(double)rand()/RAND_MAX;
y=(double)rand()/RAND_MAX;
if((x*x+y*y)<1)
partial_sum++;}

}while (local_index<N);
printf("partial_sum=%d\n",partial_sum);
pthread_mutex_lock(&mutex1);
sum+=partial_sum;
printf("sum=%d\n",sum);
pthread_mutex_unlock(&mutex1);
return;
}

main()
{
int i;
time_t start_time=0,end_time=0;
pthread_t thread[no_threads];
pthread_mutex_init(&mutex1,NULL);
start_time=time((time_t*)0);
for(i=0;i<no_threads;i++)
if(pthread_create(&thread[i],NULL,slave,NULL)!=0)
perror("Pthread_create fails");
for(i=0;i<no_threads;i++)
if(pthread_join(thread[i],NULL)!=0)
perror("Pthread_join fails");
printf("The pi is %f\n",(double)4*sum/N);
end_time=time((time_t *)0);
printf("time=%f\n",difftime(end_time,start_time));
}
看这段程序有什么毛病,为什么会运行的更慢了呢?


2007-04-27 13:50



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-135374-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.618667 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved