title: Why is a while loop needed around pthread wait conditions?
body: <p>I'm learning pthread and wait conditions. As far as I can tell a typical waiting thread is like this:</p>
  
  <pre><code>pthread_mutex_lock(&amp;m);
  while(!condition)
       pthread_cond_wait(&amp;cond, &amp;m);
  // Thread stuff here
  pthread_mutex_unlock(&amp;m);
  </code></pre>
  
  <p>What I can't understand is why the line <code>while(!condition)</code> is necessary even if I use <code>pthread_cond_signal()</code> to wake up the thread.</p>
  
  <p>I can understand that if I use <code>pthread_cond_broadcast()</code> I need to test condition, because I wake up <em>all</em> waiting threads and one of them can make the condition false again before unlocking the mutex (and thus transferring execution to another waked up thread which should not execute at that point).
  But if I use <code>pthread_cond_signal()</code> I wake up just <em>one</em> thread so the condition must be true. So the code could look like this:</p>
  
  <pre><code>pthread_mutex_lock(&amp;m);
  pthread_cond_wait(&amp;cond, &amp;m);
  // Thread stuff here
  pthread_mutex_unlock(&amp;m);
  </code></pre>
  
  <p>I read something about spurious signals that may happen. Is this (and only this) the reason? Why should I have spurious singnals? Or there is something else I don't get?</p>
  
  <p>I assume the signal code is like this:</p>
  
  <pre><code>pthread_mutex_lock(&amp;m);
  condition = true;
  pthread_cond_signal(&amp;cond); // Should wake up *one* thread
  pthread_mutex_unlock(&amp;m);
  </code></pre>