title: Increasing a global counter variable from within a thread without having to wait for each individual thread
body: <p>My goal is to create a program that evaluates the performance gains from increasing the number of threads the program can use. I evaluate the performance by using the Monte Carlo method to calculate pi. Each thread should create 1 random coordinate (x,y) and check if that coordinate is within the circle or not. If it is, the <code>inCircle</code> counter should increase. Pi is calculated as follows: <code>4 * inCircle/trys</code>. Using <code>pthread_join</code>, there is no performance gains in a problem that should benefit from multiple threads. Is there some way to allow multiple threads to increase a counter without having to wait for each individual thread? </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;pthread.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;time.h&gt;
  #include &lt;stdbool.h&gt;
  #include &lt;pthread.h&gt;
  
  #define nPoints 10000000
  #define NUM_THREADS 16
  
  int inCircle = 0;
  int count = 0;
  double x,y;
  pthread_mutex_t mutex;
  
  bool isInCircle(double x, double y){
      if(x*x+y*y&lt;=1){
          return true;
      }
      else{
          return false;
      }
  }
  
  void *piSlave(){
      int myCount = 0;
      time_t now;
      time(&amp;now);
      srand((unsigned int)now);
      for(int i = 1; i &lt;= nPoints/NUM_THREADS; i++) {
          x = (double)rand() / (double)RAND_MAX;
          y = (double)rand() / (double)RAND_MAX;
          if(isInCircle(x,y)){
              myCount++;
          }
       }
      pthread_mutex_lock(&amp;mutex);
      inCircle += myCount;
      pthread_mutex_unlock(&amp;mutex);
      pthread_exit(0);
  }
  double piMaster()
  {
      pthread_t threads[NUM_THREADS];
      int rc;
      long t;
  
      for(t=0; t&lt;NUM_THREADS; t++){
          printf("Creating thread %ld\n", t);
          rc = pthread_create(&amp;threads[t], NULL, piSlave, (void *)t);
          if (rc){
              printf("ERROR; return code from pthread_create() is %d\n", rc);
              exit(-1);
          }
      //pthread_join(threads[t], NULL);
  
      }
      //wait(NULL);
      return 4.0*inCircle/nPoints;
  }
  
  int main()
  {
      printf("%f\n",piMaster());
      return(0);
  }
  </code></pre>