gpt4 book ai didi

在 pthread 中计算 pi

转载 作者:行者123 更新时间:2023-11-30 17:54:53 36 4
gpt4 key购买 nike

我尝试使用 bpp 方法计算 pi,但结果一直为 0。整个想法是让每个线程计算其中的一部分,然后使用 join 方法将每个线程的总和相加

#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);
}

最佳答案

出于您的目的,您不需要互斥体或其他复杂的结构。只需让每个线程计算自己的局部变量即可。向每个线程提供一个 double 的地址,他在其中接收 k 并可能返回结果,就像您已经分离 ptread_t 一样> 每个线程的变量。

关于在 pthread 中计算 pi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14688685/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com