title: Thread Synchronization in Linux in C
body: <p>I am having issue synchronizing the threads so each thread can run one job first, then another thread start the same job, and so on. Below is my code: </p>
  
  <pre><code>#include &lt;unistd.h&gt;
  #include &lt;sys/types.h&gt; 
  #include &lt;errno.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;pthread.h&gt;
  #include &lt;string.h&gt;
  #include &lt;semaphore.h&gt;
  
  void handler ( void *ptr );
  sem_t mutex;
  
  int worker = 2; // number of workers
  int job = 4; // number of jobs for each worker
  
  int main()
  {
  
      int i = 0;
      pthread_t thread_a;
  
      sem_init(&amp;mutex, 0, 1);
  
      for (i; i &lt; worker; i++)
      {  
         int *n_workers = malloc(sizeof(*n_workers));  
         *n_workers = i;                   
         pthread_create (&amp;thread_a, NULL, (void *) &amp;handler, n_workers);
      }
  
      pthread_join(thread_a, NULL);
  
      sem_destroy(&amp;mutex);
  
      pthread_exit(0);
  }
  
  void handler ( void *ptr )
  {
      int x = *((int *) ptr);
      int i = 0;
  
      for (i; i &lt; job; i++)
      {
         sem_wait(&amp;mutex);
         printf("Worker %d: Doing Job %d\n", x, i);  
         sem_post(&amp;mutex);
      }
  }
  </code></pre>
  
  <p>The output is : </p>
  
  <pre><code>Worker 1: Doing Job 0
  Worker 1: Doing Job 1
  Worker 1: Doing Job 2
  Worker 1: Doing Job 3
  Worker 0: Doing Job 0
  Worker 0: Doing Job 1
  Worker 0: Doing Job 2
  Worker 0: Doing Job 3
  </code></pre>
  
  <p>In the program, each worker has 4 jobs and there are 2 workers. The problem is that worker 1 does all 4 jobs at once and worker 0 does that all jobs after it. The ideal output would be this:</p>
  
  <pre><code>Worker 0: Doing Job 0
  Worker 1: Doing Job 0
  Worker 0: Doing Job 1
  Worker 1: Doing Job 1
  Worker 0: Doing Job 2
  Worker 1: Doing Job 2
  Worker 0: Doing Job 3
  Worker 1: Doing Job 3
  </code></pre>
  
  <p>I am not sure where the issue is here, any help is greatly appreciated. Thanks</p>