title: Do I have to acquire lock before calling condition_variable.notify_one()?
body: <p>I am a bit confused about the use of <code>std::condition_variable</code>. I understand I have to create a <code>unique_lock</code> on a <code>mutex</code> before calling <code>condition_variable.wait()</code>. What I cannot find is whether I should also acquire a unique lock before calling <code>notify_one()</code> or <code>notify_all()</code>.</p>
  
  <p>Examples on <a href="http://cppreference.com" rel="noreferrer">cppreference.com</a> are conflicting. For example, the <a href="http://en.cppreference.com/w/cpp/thread/condition_variable/notify_one" rel="noreferrer">notify_one page</a> gives this example:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;condition_variable&gt;
  #include &lt;thread&gt;
  #include &lt;chrono&gt;
  
  std::condition_variable cv;
  std::mutex cv_m;
  int i = 0;
  bool done = false;
  
  void waits()
  {
      std::unique_lock&lt;std::mutex&gt; lk(cv_m);
      std::cout &lt;&lt; "Waiting... \n";
      cv.wait(lk, []{return i == 1;});
      std::cout &lt;&lt; "...finished waiting. i == 1\n";
      done = true;
  }
  
  void signals()
  {
      std::this_thread::sleep_for(std::chrono::seconds(1));
      std::cout &lt;&lt; "Notifying...\n";
      cv.notify_one();
  
      std::unique_lock&lt;std::mutex&gt; lk(cv_m);
      i = 1;
      while (!done) {
          lk.unlock();
          std::this_thread::sleep_for(std::chrono::seconds(1));
          lk.lock();
          std::cerr &lt;&lt; "Notifying again...\n";
          cv.notify_one();
      }
  }
  
  int main()
  {
      std::thread t1(waits), t2(signals);
      t1.join(); t2.join();
  }
  </code></pre>
  
  <p>Here the lock is not acquired for the first <code>notify_one()</code>, but is acquired for the second <code>notify_one()</code>. Looking though other pages with examples I see different things, mostly not acquiring the lock.</p>
  
  <ul>
  <li>Can I choose myself to lock the mutex before calling <code>notify_one()</code>, and why would I choose to lock it?</li>
  <li>In the example given, why is there no lock for the first <code>notify_one()</code>, but there is for subsequent calls. Is this example wrong or is there some rationale?</li>
  </ul>