title: How To Use Condition Variable
body: <p>The Linux Programming Interface book has a piece of code (producer/consumer) to show how condition variable works:</p>
  
  <pre><code>static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
  static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
  
  static int avail = 0;
  
  while (TRUE) {
      s = pthread_mutex_lock(&amp;mtx);
  
      while (avail == 0) {   /* Wait for something to consume */
         s = pthread_cond_wait(&amp;cond, &amp;mtx);
      }
  
      while (avail &gt; 0) {   /* Consume all available units */ 
          avail--;
      }
  
      s = pthread_mutex_unlock(&amp;mtx);
  }
  </code></pre>
  
  <p>Why we use <code>pthread_mutex_lock</code> in <code>while</code>? why we don't use it in an <code>if</code>?</p>