title: POSIX C Threads. Mutex example. Don't work as expected
body: <p>I have a big problem, I can't figure out why mutexes in C don't work as I expect.
  This is my code:</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;pthread.h&gt;
  
  pthread_t mythread;
  pthread_mutex_t mymutex;
  
  void *anotherFunc(void*)
  {
      pthread_mutex_lock(&amp;mymutex);
  
      for(int i = 0; i &lt; 100; i++)
          printf("anotherFunc\n");
  
      pthread_mutex_unlock(&amp;mymutex);
  
      pthread_exit(NULL);
  }
  
  void *func(void*)
  {
      pthread_mutex_lock(&amp;mymutex);
  
      for(int i = 0; i &lt; 100; i++)
          printf("func\n");
  
      pthread_mutex_unlock(&amp;mymutex);
  
      pthread_exit(NULL);
  }
  
  int main(int argc, char *argv[])
  {
      pthread_mutex_init(&amp;mymutex, NULL);
  
      pthread_create(&amp;mythread, NULL, func, NULL);
      pthread_create(&amp;mythread, NULL, anotherFunc, NULL);
  
      pthread_mutex_destroy(&amp;mymutex);
  
      pthread_exit(NULL);
      return EXIT_SUCCESS;
  }
  </code></pre>
  
  <p>What I expect to happen is the program to print first 100 "func" messages and then 100 "anotherFunc" messages. What I expect is execution to reach func and lock the mutex. When the execution reaches anotherFunc, I expect to wait until func unlocks the mutex. But I get interfered messages like </p>
  
  <p>func
  func
  func
  anotherFunc
  anotherFunc
  anotherFunc
  func
  anotherFunc</p>
  
  <p>I don't understand how this thing works. Please help!</p>