title: c++ 11 condition_variable wait spurious wake up is not working
body: <p>I tried to write a simple producer/consumer by using <code>condition_variable</code>,</p>
  
  <pre><code>include &lt;iostream&gt;
  #include &lt;thread&gt;
  #include &lt;condition_variable&gt;
  #include &lt;mutex&gt;
  #include &lt;chrono&gt;
  #include &lt;queue&gt;
  #include &lt;chrono&gt;
  using namespace std;
  
  condition_variable cond_var;
  mutex m;
  int main()
  {
      int c = 0;
      bool done = false;
      cout &lt;&lt; boolalpha;
      queue&lt;int&gt; goods;
  
      thread producer([&amp;](){
          for (int i = 0; i &lt; 10; ++i) {
              m.lock();
              goods.push(i);
              c++;
              cout &lt;&lt; "produce " &lt;&lt; i &lt;&lt; endl;
              m.unlock();
              cond_var.notify_one();
              this_thread::sleep_for(chrono::milliseconds(100));
          }
          done = true;
          cout &lt;&lt; "producer done." &lt;&lt; endl;
          cond_var.notify_one();
      });
  
      thread consumer([&amp;](){
          unique_lock&lt;mutex&gt; lock(m);
          while(!done || !goods.empty()){
              /*
              cond_var.wait(lock, [&amp;goods, &amp;done](){
                          cout &lt;&lt; "spurious wake check" &lt;&lt; done &lt;&lt;endl;
                          return (!goods.empty() || done);
              });
              */  
              while(goods.empty())
              {
                  cout&lt;&lt; "consumer wait" &lt;&lt;endl;
                  cout&lt;&lt; "consumer owns lock " &lt;&lt; lock.owns_lock() &lt;&lt;endl;
                  cond_var.wait(lock);
              }
              if (!goods.empty()){
                  cout &lt;&lt; "consume " &lt;&lt; goods.front()&lt;&lt;endl;
                  goods.pop();
                  c--;
              }
          }
      });
  
      producer.join();
      consumer.join();
      cout &lt;&lt; "Net: " &lt;&lt; c &lt;&lt; endl;
  }
  </code></pre>
  
  <p>The problem I have now is when the consumer consumes the last item before the producer set <code>done</code> to <code>true</code>, the consumer thread will stuck in </p>
  
  <pre><code> while(goods.empty())
              {
                  cout&lt;&lt; "consumer wait" &lt;&lt;endl;
                  cout&lt;&lt; "consumer owns lock " &lt;&lt; lock.owns_lock() &lt;&lt;endl;
                  cond_var.wait(lock);
              }
  </code></pre>
  
  <p>My understanding is <code>cond_var.wait(lock)</code> will wake up spuriously and thus exit the <code>while(good.empty())</code> loop, but it seems not the case?</p>