-1

I m doing thread programming and trying to implement MonteCarlo technique for calculating Pi value in it. I compiled the code and I have no error but when I execute I get no output for it. Kindly correct me if there's any mistake.

Here's my code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>

#define frand() ((double) rand() / (RAND_MAX))
#define MAX_LEN 1353
const size_t N = 4;
float circlePoints=0;
void* point_counter(void *param){
    float xcord; 
    float ycord; 
    while(MAX_LEN){

        xcord=frand();
        ycord=frand();
        float cord = (xcord*xcord) + (ycord*ycord);

        if(cord <= 1){
            circlePoints++;}
    }
}

int main()
{
    printf("out");
    size_t i;
    pthread_t thread[N];

    srand(time(NULL));
    for( i=0;i <4;++i){
        printf("in creating thread");
        pthread_create( &thread[i], NULL, &point_counter, NULL);
    }
    for(i=0;i <4;++i){
        printf("in joining thread");
        pthread_join( thread[i], NULL );
    }
    for( i=0;i <4;++i){
        printf("in last thread");
        float pi = 4.0 * (float)circlePoints /MAX_LEN;

        printf("pi is %2.4f: \n", pi);
    }
    return 0;
}
johnsyweb
  • 136,902
  • 23
  • 188
  • 247

3 Answers3

4

You're hitting an infinite loop here:

while(MAX_LEN){

Since MAX_LEN is and remains non-zero.

As to why you see no output before that, see Why does printf not flush after the call unless a newline is in the format string?

Community
  • 1
  • 1
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
2

You have an infinite loop in your thread function:

while(MAX_LEN){
   ...
}

So all the threads you create never come out that loop.

Also, circlePoints is modified by all the threads which will lead to race condition ( what's a race condition? ) and likely render the value incorrect. You should use a mutex lock to avoid it.

Community
  • 1
  • 1
P.P
  • 117,907
  • 20
  • 175
  • 238
1
while(any_non_zero_number_which does_not_update)
{
    infinite loop            //not good unless you intend it that way
}
Barath Ravikumar
  • 5,658
  • 3
  • 23
  • 39