나는 bailey-borwein-plouffe 공식을 사용하여 pi의 값을 계산하는 프로그램을 작성하고 있습니다. 내 문제는 뮤텍스를 사용하여이 코드를 실행할 때마다 계속 다른 결과를 얻고 있습니다. 파이 함수 정의의 뮤텍스 잠금이 하나의 리소스 pi에만 사용되어야하는지 확실하지 않습니다.mutex를 사용하여이 프로그램을 동시에 실행할 때마다 다른 결과가 발생합니다.
enter code here
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#define NUM_THREADS 1000
void *pie_function(void * p);//returns the value of pie
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; //creates a mutex variable
double pi=0,p16=1;
main()
{
pthread_t threads[NUM_THREADS]; //creates the number of threads using 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],NULL);
if(iret1){
printf("ERROR; return code from pthread_create() is %d\n", iret1);
exit(-1);
}
}
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 *s){
int rc;
int k=(int) s;
pthread_mutex_lock(&mutex1); //locks the share variable pi and p16
pi += 1.0/p16 * (4.0/(8*k + 1) - 2.0/(8*k + 4) - 1.0/(8*k + 5) - 1.0/(8*k+6));
p16 *=16;
rc=pthread_mutex_unlock(&mutex1);
if(rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
절대적으로 맞습니다. 스레드를 사용하여 구현하고 싶습니다. 무엇을 잘못하고 있는지 확인하고 싶습니다. – user1850254
@ user1850254, 당신이 잘못하고있는 것은 (쓰레딩이 필요하다면) 스레드가'k'의 순차적 인 값으로 작업을한다고 가정하고 있습니다 (user315052의 답 참조). 내 논쟁은 스레드가이 사용 사례에서 나쁜 생각이라는 것입니다. 스레딩을 배우고 싶다면 최소한 적절한 노력 영역을 선택하십시오 :-) – paxdiablo
@ 파이 도움말을 계산하는 공식을 변경해야합니까? – user1850254