title: possible causes of infinite wait in pthread_cond_wait
body: <p>I am currently trying to analyse a issue in third party source code where a thread (code snippet corresponding to <code>THREAD-T1</code>) is in infinite wait state. The suspicion is that the thread is stuck in <code>pthread_cond_wait</code>. The following are the details of the same.</p>
  
  <p><strong>Code description</strong></p>
  
  <ul>
  <li>T1 does an asynchronous call to an API exposed by T2.</li>
  <li>Hence T1 moves to a blocking wait on a conditional variable (say <code>cond_t</code>).</li>
  <li>The conditional variable <code>cond_t</code> is signalled in the callback event generated by T2.</li>
  <li>The above cycle is repeated <code>n</code> times until the API returns success.</li>
  </ul>
  
  <p>To consolidate, the above is a series of steps which makes the asynchronous call similar to a synchronous one by the use of condition variables.</p>
  
  <p><strong>Sample code</strong></p>
  
  <pre><code>   #define MAX_RETRY (3)
     bool            g_b_ret_val;       
     pthread_mutex_t g_cond_mutex;
     pthread_mutex_t g_ret_val_mutex; /* Assume iniitailzed in the main thread */
     pthread_cond_t  g_cond_t; /* Assume iniitailzed in the main thread */
  
     retry_async_call_routine()  /* Thread-T1 */
     {
         while(( false == g_b_ret_val) &amp;&amp; (retry &lt; MAX_RETRY))
         {
             (void)invoke_async_api();
             pthread_mutex_init(&amp;g_cond_mutex, NULL);
             pthread_mutex_lock(&amp;g_cond_mutex);
             pthread_cond_wait(g_cond_t, &amp;g_cond_mutex);
             pthread_mutex_unlock(&amp;g_cond_mutex);
             pthread_mutex_destroy(&amp;g_cond_mutex);
             retry ++ ;
          }
     }
  
     callback_routine() /* Thread-T2 */
     {
          pthread_mutex_lock(&amp;g_ret_val_mutex);
          g_b_ret_val = true; /* May be false also on failure */
          pthread_mutex_unlock(&amp;g_ret_val_mutex);
          pthread_cond_signal(&amp;g_cond_t);
     }
  </code></pre>
  
  <p><strong>Known issues that I see in the code</strong></p>
  
  <ol>
  <li>Missing retest of condition in a while loop on <code>pthread_cond_wait</code></li>
  <li>Missing mutex lock while signalling</li>
  </ol>
  
  <p><strong>Questions</strong></p>
  
  <ol>
  <li>Please point out me on any more loop holes (or) possibility of infinite wait (if any).</li>
  <li><code>g_cond_t</code> is not reset using <code>pthread_cond_destroy</code> between successive waits, what is  the behaviour of the same ? ( Any references regarding this)</li>
  </ol>