0
我想用bpp方法计算pi,但是我的结果一直保持为0.整个想法是为每个线程计算它的一部分,并且使用连接方法在pthreads中计算pi
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#define NUM_THREADS 20
void *pi_function(void *p);//returns the value of pi
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; //creates a mutex variable
double pi=0,p16=1;int k=0;
double sumvalue=0,sum=0;
main()
{
pthread_t threads[NUM_THREADS]; //creates the number of threads NUM_THREADS
int iret1; //used to ensure that threads are created properly
//pthread_create(thread,attr,start_routine,arg)
int i;
pthread_mutex_init(&mutex1, NULL);
for(i=0;i<NUM_THREADS;i++){
iret1= pthread_create(&threads[i],NULL,pie_function,(void *) i);
if(iret1){
printf("ERROR; return code from pthread_create() is %d\n", iret1);
exit(-1);
}
}
for(i=0;i<NUM_THREADS;i++){
iret1=pthread_join(threads[i],&sumvalue);
if(iret1){
printf("ERROR; return code from pthread_create() is %d\n", iret1);
exit(-1);
}
pi=pi+sumvalue; //my result here keeps returning 0
}
pthread_mutex_destroy(&mutex1);
printf("Main: program completed. Exiting.\n");
printf("The value of pi is : %f\n",pi);
exit(0);
}
void *pie_function(void * p){
int rc;
int k=(int)p;
sumvalue += 1.0/p16 * (4.0/(8* k + 1) - 2.0/(8*k + 4)
- 1.0/(8*k + 5) - 1.0/(8*k+6));
pthread_mutex_lock(&mutex1); //locks the share variable pi and p16
p16 *=16;
rc=pthread_mutex_unlock(&mutex1);
if(rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
}
pthread_exit(&sumvalue);
}
首先,请修复您的代码缩进/空格,以使其可读。 –
你是否试图在所有线程之间共享一个'sumvalue'变量?我认为每个人都需要自己的本地总和,然后再加上全球总和。但是你至少应该验证你的实现是否在一个线程上工作,如果你还没有的话。 – Rup
@Rup可能是问题,并有资格作为答案,IMO。 *一个线程*建议本身值得+1。 –