当前位置: 代码迷 >> C语言 >> [求助]多线程概率法求解pi值
  详细解决方案

[求助]多线程概率法求解pi值

热度:303   发布时间:2007-04-27 13:50:20.0
[求助]多线程概率法求解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; }
将该程序用多线程实现,我刚开始学习线程,请高手帮忙,最好能把程序写上,谢谢大家了!望大家不吝赐教!!
搜索更多相关的解决方案: 线程  概率  求解  

----------------解决方案--------------------------------------------------------

#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));
}
看这段程序有什么毛病,为什么会运行的更慢了呢?



----------------解决方案--------------------------------------------------------
  相关解决方案