title: Issues regarding mutexes on POSIX threads
body: <p>I'm having some issues with the following code. I just can't seem to find the bug:</p>
  
  <pre><code>     1  #include &lt;pthread.h&gt;
       2  #include &lt;stdio.h&gt;
       3  #include &lt;stdlib.h&gt;
       4  #include &lt;unistd.h&gt;
       5  
       6  struct bla
       7  {
       8      pthread_mutex_t mut;
       9      int x;
      10  };
      11  
      12  
      13  pthread_t tid;
      14  
      15  void *thr_fn1 (struct bla *fp);
      16  
      17  int main()
      18  {
      19      struct bla *fp;
      20      fp = (struct bla *) malloc (sizeof(struct bla));
      21      fp-&gt;x=3;
      22      printf ("Initializing mutex_init\n");
      23      pthread_mutex_init (&amp;fp-&gt;mut,NULL);
      24      pthread_create (&amp;tid,NULL,thr_fn1,fp);
      25      sleep (2);
      26      printf ("Main thread ended sleep. Incrementing.\n");
      27      fp-&gt;x++;
      28      pthread_join (tid,NULL);
      29      printf ("x=%d\n",fp-&gt;x);
      30      pthread_mutex_destroy(&amp;fp-&gt;mut);
      31      return 0;
      32  
      33  }
      34  
      35  void *thr_fn1 (struct bla *fp)
      36  {
      37      printf ("Locking new thread!\n");
      38      pthread_mutex_lock (&amp;fp-&gt;mut);
      39      printf ("Sleeping.\n");
      40      sleep (5);
      41      pthread_mutex_unlock (&amp;fp-&gt;mut);
      42      printf ("Thread unlocked.\n");
      43      return ((void *) 0);
      44  }
  </code></pre>
  
  <p>Why does the value still get incremented at line 27? Shouldn't it be protected by the mutex in the second thread by the lock (line 38)?</p>
  
  <p>Thanks!</p>