title: pthread_mutex_unlock not atomic
body: <p>I've the following source code (adapted from my original code):</p>
  
  <pre><code>#include "stdafx.h"
  #include &lt;stdlib.h&gt; 
  #include &lt;stdio.h&gt; 
  
  #include "pthread.h"
  
  #define MAX_ENTRY_COUNT 4  
  
  int  entries = 0;  
  bool start = false;
  
  bool send_active = false;
  
  pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;  
  pthread_cond_t condNotEmpty = PTHREAD_COND_INITIALIZER;  
  pthread_cond_t condNotFull = PTHREAD_COND_INITIALIZER;  
  
  void send()
  { 
      for (;;) {
          if (!start)
              continue;
          start = false;
  
          for(int i = 0; i &lt; 11; ++i) { 
              send_active = true;
  
              pthread_mutex_lock(&amp;mutex); 
              while(entries == MAX_ENTRY_COUNT) 
                  pthread_cond_wait(&amp;condNotFull, &amp;mutex);      
              entries++; 
              pthread_cond_broadcast(&amp;condNotEmpty); 
              pthread_mutex_unlock(&amp;mutex);
  
              send_active = false;
          }
      }
  } 
  
  void receive(){ 
      for(int i = 0; i &lt; 11; ++i){ 
          pthread_mutex_lock(&amp;mutex);  
          while(entries == 0) 
              pthread_cond_wait(&amp;condNotEmpty, &amp;mutex); 
          entries--;  
          pthread_cond_broadcast(&amp;condNotFull);  
          pthread_mutex_unlock(&amp;mutex);
      } 
  
      if (send_active)
          printf("x");
  } 
  
  int _tmain(int argc, _TCHAR* argv[])
  {
      pthread_t s; 
  
      pthread_create(&amp;s, NULL, (void *(*)(void*))send, NULL);  
  
      for (;;) {
          pthread_mutex_init(&amp;mutex, NULL);
          pthread_cond_init(&amp;condNotEmpty, NULL);
          pthread_cond_init(&amp;condNotFull, NULL);
  
          start = true;
  
          receive();
  
          pthread_mutex_destroy(&amp;mutex);
          mutex = NULL;
          pthread_cond_destroy(&amp;condNotEmpty);
          pthread_cond_destroy(&amp;condNotFull);
          condNotEmpty = NULL;
          condNotFull = NULL;
  
          printf(".");
      }
  
      return 0;
  }
  </code></pre>
  
  <p>The problem is like follows: from time to time the last unlock in the send function is not finished before the receive method continues. In my original code the mutexes are located in an objects which are deleted after doing the job. If the send method has not finished with the last unlock then the mutexes are invalid and my program causes failures in unlock.</p>
  
  <p>The behavior can be easily reproduced by running the program: each time the "x" is diplayed the receive method has nearly finished and the send method "hangs" in the unlock call.</p>
  
  <p>I've compiled with VS2008 and VS2010 - both results are same.</p>
  
  <p>pthread_mutex_unlock is not atomic, this would solve the problem. How can I solve this issue? Any comments are welcome...</p>
  
  <p>Best regards</p>
  
  <p>Michael</p>