title: Condition variables and mutex_unlock
body: <p>Code:</p>
  
  <pre><code>void *inc_func(void *arg)
  {
      pthread_mutex_lock(&amp;mutex);
      pthread_cond_signal(&amp;count_threshold_cv);
      sleep(1);
      pthread_mutex_unlock(&amp;mutex);
  }
  void *watch(void *arg)
  {
      pthread_mutex_lock(&amp;mutex);
      pthread_cond_wait(&amp;count_threshold_cv,&amp;mutex);
      sleep(1);
      pthread_mutex_unlock(&amp;mutex);
  }
  int main()
  {
      pthread_t id[2];
      pthread_create(&amp;id[0],NULL,watch,NULL);
      pthread_create(&amp;id[1],NULL,inc_func,NULL);
      int i;
      for(i=0;i&lt;2;i++)
          pthread_join(id[i],NULL);
  }
  </code></pre>
  
  <p>Now we have one <code>mutex_unlock</code> function to be executed in each thread. And one locked mutex. Why doesn't this lead to an <code>undefined behaviour</code>. Since both threads try to unlock the same mutex which leads to one trying to unlock an already unlocked mutex.</p>
  
  <p>Edit: <code>pthread_cond_wait</code> releases the <code>mutex</code> for the second thread to use. Now consider the second thread executes <code>pthread_cond_signal</code> which leads to the first thread to reacquire the <code>mutex</code>. Now we have two threads having the same <code>mutex</code> lock,because both didn't get to execute the <code>mutex_unlock</code> because of the 'sleep' function. Is my understanding wrong?</p>