title: C Threads - Sync
body: <p>I have this code, I am trying to create n threads, Do some work in each thread, and then reap each thread. If n thread is even, use detach, and if odd, use join, </p>
  
  <p>When i run the program, it first prints out Successfully reaped thread, then doing working, then successfully reaped thread... looks like i have some synchronization issues</p>
  
  <p>Do I even need to use Mutex?
  Can anyone help me with getting everything running in the right order?</p>
  
  <p>Thank you</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;pthread.h&gt;
  
  pthread_mutex_t lock;
  
  void *dowork(){
      //Do whatever needs to be done in each thread here
      pthread_mutex_lock(&amp;lock);
      long tid = (long) pthread_self();
      printf("Doing Work ...for %ld\n",tid);
      pthread_mutex_unlock(&amp;lock);
  
      //pthread_exit(NULL);
      return;
  }
  
  void spawn(int n){
       if (pthread_mutex_init(&amp;lock, NULL) != 0)
      {
          printf("\n mutex init failed\n");
          exit (1);
      }
      int i=0;
      //pthread_t * thread = malloc(sizeof(pthread_t)*n);
      pthread_t threads[n];
       while (i&lt;n) {
          if(pthread_create(&amp;(threads[i]), NULL, dowork, NULL) != 0){
              printf ("Create pthread error!\n");
              exit (1);
          }
          i++;
      }//End of while
  
      // Wait for threads to complete //
      i = 0;
      while (i&lt;n) 
      {
          int success = -1;
  
          if(i%2 == 0){
              success=pthread_detach(threads[i]);
          }
          else{
              success=pthread_join(threads[i], NULL);
              }
          if(success==0)
              printf("Succesfully reaped thread\n");
          i++;
      }
        pthread_mutex_destroy(&amp;lock);
  
  }
  
  
  int main() {
      spawn(5);
  }
  </code></pre>