title: Safe cancellation of pthreads using a cleanup handler in C
body: <p>We've been given some code to look at in preparation for an exam regarding pthreads and cancelling them properly. We've been asked to both explain what is wrong, and fix it. </p>
  
  <p>My answer: The thread handler function enters a wait state without releasing the mutex, but I feel like I'm missing something. Here is the code, the lines adding a clean up handler were added to fix the program. Again, I'm not quite sure WHY this works. (I understand the concept of the clean up handler, but I don't understand why it fixes this particular problem - another reason why I'm not sure that my answer is correct)</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;pthread.h&gt;
  
  pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  pthread_cond_t cv = PTHREAD_COND_INITIALIZER;
  const int flag = 1;
  
  static void * cancelme(void *bb_in)
  {
    pthread_mutex_lock(&amp;mutex);
  
    /* Install a cleanup handler */
    pthread_cleanup_push(pthread_mutex_unlock, &amp;mutex);
  
    while (flag) {
      pthread_cond_wait(&amp;cv, &amp;mutex);
    }
  
    //before insertion of cleanup handlers: pthread_mutex_unlock(&amp;mutex); was here
  
    /* Uninstall cleanup handler */
    pthread_cleanup_pop(1);
  
  
  
    return (NULL);
  }
  
  int main()
  {
    pthread_t t;
    pthread_create(&amp;t, NULL, cancelme, NULL);
    sleep(1);
    pthread_cancel(t);
  
    printf("Waiting for thread to finish...\n");
    pthread_join(t, NULL);
    printf("Thread finished...\n");
  
    printf("Waiting to acquire lock...\n");
    pthread_mutex_lock(&amp;mutex);
    printf("Lock acquired\n");
  
    return (0);
  }
  </code></pre>
  
  <p>Any feedback much appreciated. </p>