compute pi value using monte carlo method multithreading


I am trying to find value of PI using montecarlo method, and using parallel C code. i have write serail code and works fine. But the parallel code gives me wrong values of pi some times 0 or minus values.
please i need help

my code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <pthread.h>
 #include <stdio.h>
#include <stdlib.h>
#include <math.h>
 #define NUM_THREADS 4 //number of threads
#define TOT_COUNT 10000055 //total number of iterations



void *doCalcs(void *threadid)
{
long longTid;
longTid = (long)threadid;
int tid = (int)longTid; //obtain the integer value of thread id
//using malloc for the return variable in order make
//sure that it is not destroyed once the thread call is finished
float *in_count = (float *)malloc(sizeof(float));
*in_count=0;
unsigned int rand_state = rand();
//get the total number of iterations for a thread
float tot_iterations= TOT_COUNT/NUM_THREADS;
int counter=0;
//calculation
for(counter=0;counter<tot_iterations;counter++){
    //float x = (double)random()/RAND_MAX;
    //float y = (double)random()/RAND_MAX;
    //float result = sqrt((x*x) + (y*y));
    double x = rand_r(&rand_state) / ((double)RAND_MAX + 1) * 2.0 - 1.0;
    double y = rand_r(&rand_state) / ((double)RAND_MAX + 1) * 2.0 - 1.0;
    float result = sqrt((x*x) + (y*y));
    if(result<1){
        *in_count+=1; //check if the generated value is inside a unit circle
    }
}
//get the remaining iterations calculated by thread 0
 if(tid==0){
      float remainder = TOT_COUNT%NUM_THREADS;
      for(counter=0;counter<remainder;counter++){
            float x = (double)random()/RAND_MAX;
         float y = (double)random()/RAND_MAX;
          float result = sqrt((x*x) + (y*y));
        if(result<1){
            *in_count+=1; //check if the generated value is inside a unit circle
        }
    }
}
 }


 int main(int argc, char *argv[])
  {
    pthread_t threads[NUM_THREADS];
   int rc;
   long t;
   void *status;
    float tot_in=0;
     for(t=0;t<NUM_THREADS;t++){
      rc = pthread_create(&threads[t], NULL, doCalcs, (void *)t);
      if (rc){
    printf("ERROR; return code from pthread_create() is %d\n", rc);
    exit(-1);
     }
}
//join the threads
for(t=0;t<NUM_THREADS;t++){
pthread_join(threads[t], &status);
//printf("Return from thread %ld is : %f\n",t, *(float*)status);
tot_in+=*(float*)status; //keep track of the total in count
}
printf("Value for PI is %f \n",1, 4*(tot_in/TOT_COUNT));
/* Last thing that main() should do */
pthread_exit(NULL);
  }            
Last edited on
Your threads doesn't return a defined value.

See
pthread_exit(3)
.
Topic archived. No new replies allowed.