title: Deadlock prevent
body: <p>Need help how to prevent the deadlock for the code in blow i have written. or any suggestion i need to fix the code in order to get rid of deadlock?
  also when i run in Linux i got a Segmentation fault (core dumped).</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;stdbool.h&gt;
  #include &lt;pthread.h&gt;
  #include &lt;semaphore.h&gt;
  
  int cnt;
  int *bites;
  int *old_bites;
  sem_t *sticks;
  
  void *roger(void *arg) {
      int rog = *(int*)arg;
  
      for(;;) {
          sem_wait(&amp;(sticks[rog]));             // left
          sem_wait(&amp;(sticks[(rog + 1) % cnt])); // right
  
          bites[rog]++;
  
          sem_post(&amp;(sticks[(rog + 1) % cnt])); // right
          sem_post(&amp;(sticks[rog]));             // left
  }
  
  pthread_exit(NULL);
  
  return NULL;
  }
  
  int main(int argc, char *argv[]) {
  
  int i;
  pthread_t *rogers;
  int *pos;
  cnt = (int)strtol(argv[1], NULL, 10);
  
  rogers = (pthread_t *)calloc(cnt, sizeof(pthread_t));
  pos = (int *)malloc(cnt * sizeof(int));
  bites = (int *)calloc(cnt, sizeof(int));
  old_bites = (int *)calloc(cnt, sizeof(int));
  sticks = (sem_t *)calloc(cnt, sizeof(sem_t));
  
  for(i = 0; i &lt; cnt; i++) {
      sem_init(&amp;(sticks[i]), 0, 1);
  }
  
  for(i = 0; i &lt; cnt; i++) {
      pos[i] = i;
      pthread_create(&amp;(rogers[i]), NULL, roger, (void *)&amp;pos[i]);
  }
  
  for(;;) {
      bool dead = true;
      usleep(50000);
      for(i = 0; i &lt; cnt; i++) {
          if(bites[i] != old_bites[i]) {
              dead = false;
          }
      }
      if(dead) {
          exit(EXIT_SUCCESS);
      }
  
      for(i = 0; i &lt; cnt; i++) {
          printf("%8X", bites[i]);
      }
      printf("\n");
      for(i = 0; i &lt; cnt; i++) {
          old_bites[i] = bites[i];
      }
  }
  
  for(i = 0; i &lt; cnt; i++) {
      pthread_join(rogers[i], NULL);  
  }
  
  for(i = 0; i &lt; cnt; i++) {
      sem_destroy(&amp;(sticks[i]));
  }
  
  exit(EXIT_SUCCESS);
  }
  </code></pre>