title: condition_variable wait on lock
body: <p>I try to use condition_variable with unique_lock from stl.</p>
  
  <p>But it fails on spin() function. As I can understand it was an interlocking problem. But I can't understand why.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;queue&gt;
  #include &lt;thread&gt;
  #include &lt;mutex&gt;
  #include &lt;condition_variable&gt;
  
  void spin();
  
  bool stop = false;
  bool done = false;
  
  std::thread th(spin);
  std::mutex mutex;
  std::condition_variable cv;
  
  
  void join() 
  {
      {
          std::unique_lock&lt;std::mutex&gt; lock(mutex);
          stop = true;
      }
  
      cv.notify_one();
  
      th.join();
  }
  
  void set_done()
  {
      {
          std::unique_lock&lt;std::mutex&gt; lock(mutex);
  
          std::cout &lt;&lt; "setting done" &lt;&lt; std::endl;
  
          done = true;
      }
  
      cv.notify_one();
  }
  
  void spin()
  {
      while (true)
      {
          std::unique_lock&lt;std::mutex&gt; lock(mutex);
  
          if (done)
          {
              std::cout &lt;&lt; "done..." &lt;&lt; std::endl;
              continue;
          }
  
          if (stop)
          {
              return;
          }
  
          cv.wait(lock);
      }
  }
  
  int main(int argc, char* argv[])
  {
      set_done();
  
      join();
  
      return 0;
  }
  </code></pre>
  
  <p>Code above just wrotes "setting done" and fails with runtime error. </p>
  
  <p>Why did spin's lock fails when set_done unlock the mutex already?</p>