title: Synchronizing two pthreads using mutex in C
body: <p>Need help with synchronizing two threads with mutex. Iam new to C and mutexes and Im not sure what to do here. The code has two threads that counts to ten and prints out each number, but is not synch, so it will not print synchronized, it is half synched. Means that i only get trouble in the end, sometimes it prints 8..9..11, 8..9..10..10 and so on.</p>
  
  <p>I cannot make changes to the raw code, if you take away the lines about mutexes, that is the raw code. I can only add lines about mutexes.</p>
  
  <pre><code>#include &lt;pthread.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  pthread_mutex_t mutex;
  
  int g_ant = 0;
  
  void *writeloop(void *arg) {
      while(g_ant &lt; 10) {
          pthread_mutex_lock(&amp;mutex);
          g_ant++;
          usleep(rand()%10);
          printf("%d\n", g_ant);
          pthread_mutex_unlock(&amp;mutex);
      }
      exit(0);
  }
  
  int main(void)
  {
      pthread_t tid;
      pthread_mutex_init(&amp;mutex, NULL);
      pthread_create(&amp;tid, NULL, writeloop, NULL);
      writeloop(NULL);
      pthread_join(tid, NULL);
      pthread_mutex_destroy(&amp;mutex);
      return 0;
  }
  </code></pre>