title: Why do both the notify and wait function of a std::condition_variable need a locked mutex
body: <p>On my neverending quest to understand <code>std::contion_variable</code>s  I've run into the following. On <a href="http://www.cplusplus.com/reference/condition_variable/condition_variable/" rel="nofollow">this page</a> it says the following:</p>
  
  <pre><code>void print_id (int id) {
    std::unique_lock&lt;std::mutex&gt; lck(mtx);
    while (!ready) cv.wait(lck);
    // ...
    std::cout &lt;&lt; "thread " &lt;&lt; id &lt;&lt; '\n';
  }
  </code></pre>
  
  <p>And after that it says this:</p>
  
  <pre><code>void go() {
    std::unique_lock&lt;std::mutex&gt; lck(mtx);
    ready = true;
    cv.notify_all();
  }
  </code></pre>
  
  <p>Now as I understand it, both of these functions will halt on the <code>std::unqique_lock</code> line. Until a unique lock is acquired. That is, no other thread has a lock. </p>
  
  <p>So say the <code>print_id</code> function is executed first. The unique lock will be aquired and the function will halt on the wait line.</p>
  
  <p>If the <code>go</code> function is then executed (on a separate thread), the code there will halt on the unique lock line. Since the mutex is locked by the <code>print_id</code> function already. </p>
  
  <p>Obviously this wouldn't work if the code was like that. But I really don't see what I'm not getting here. So please enlighten me.</p>