title: Thread sync by using mutex and barrier in C
body: <p>I am trying to use pthread mutex variables and barrier to synchronize the output of my program, but it is not working the way I want it to. Each thread is seeing its final value every 20 values (coming from the for loop) which is alright but I'm trying to make them all get to the same final value (if using 5 threads, all of them should see 100 as final value, with 4 threads, 80, etc)</p>
  
  <pre><code>#include &lt;pthread.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt; 
  
  pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
  
  int SharedVariable =0;
  void *SimpleThread(void *args)
  {
      int num,val,rc;
      int which =(int)args;
      rc = pthread_mutex_lock(&amp;mutex1);
      for(num=0; num&lt;20; num++){
  #ifdef PTHREAD_SYNC
          if(random() &gt; RAND_MAX / 2)
              usleep(10);
  #endif
          //pthread_mutex_lock(&amp;mutex1);
          val = SharedVariable;
          printf("*** thread %d sees value %d\n", which, val);
          //pthread_mutex_lock(&amp;mutex1);
          SharedVariable = val+1;
          pthread_mutex_unlock(&amp;mutex1);
      }   
      val=SharedVariable;
  
      printf("Thread %d sees final value %d\n", which, val);
      //pthread_mutex_destroy(&amp;mutex1);
      //pthread_exit((void*) 0);
      //pthread_mutex_unlock(&amp;mutex1);
  
  }
  
  int main (int argc, char *argv[])
  {
     if(atoi(argv[1]) &gt; 0){        
     int num_threads = atoi(argv[1]);  
     //pthread_mutex_init(&amp;mutex1, NULL);
     pthread_t threads[num_threads];
     int rc;
     long t;
     rc = pthread_mutex_lock(&amp;mutex1);
     for(t=0; t&lt; num_threads; t++){
        printf("In main: creating thread %ld\n", t);
        rc = pthread_create(&amp;threads[t], NULL, SimpleThread, (void* )t);
        if (rc){
           printf("ERROR; return code from pthread_create() is %d\n", rc);
           exit(-1);
        }
  
      //pthread_join(thread1);
  
     }
      rc= pthread_mutex_unlock(&amp;mutex1);
  }
     else{
        printf("ERROR: The parameter should be a valid positive number.");
        exit(-1);
    }
  
     pthread_mutex_destroy(&amp;mutex1);
     pthread_exit(NULL);
  }
  </code></pre>
  
  <p>Any suggestions or help is greatly appreciated!
  Thanks in advanced!</p>