title: C++ condition variable notify_one: before or after release lock?
body: <p>Below is some code example about C++ condition variable from <a href="https://en.cppreference.com/w/cpp/thread/condition_variable" rel="nofollow noreferrer">CPPConference.com</a>:</p>
  
  <pre><code>std::mutex m;
  std::condition_variable cv;
  std::string data;
  bool ready = false;
  bool processed = false;
  
  void worker_thread()
  {
      // Wait until main() sends data
      std::unique_lock&lt;std::mutex&gt; lk(m);
      cv.wait(lk, []{return ready;});
  
      // after the wait, we own the lock.
      std::cout &lt;&lt; "Worker thread is processing data\n";
      data += " after processing";
  
      // Send data back to main()
      processed = true;
      std::cout &lt;&lt; "Worker thread signals data processing completed\n";
  
      // Manual unlocking is done before notifying, to avoid waking up
      // the waiting thread only to block again (see notify_one for details)
      lk.unlock();
      cv.notify_one();
  }
  </code></pre>
  
  <p>I do not quite understand the part at the end where the lock is released before the other thread is notified. </p>
  
  <ol>
  <li>Does it work if the code put cv.notify_one() before lk.unlock()?</li>
  <li>Why is it a better practice to put cv.notify_one() after lk.unlock()? According to <a href="https://en.cppreference.com/w/cpp/thread/condition_variable/notify_one" rel="nofollow noreferrer">this page</a>, "The notifying thread does not need to hold the lock on the same mutex as the one held by the waiting thread(s); in fact doing so is a pessimization, since the notified thread would immediately block again, waiting for the notifying thread to release the lock." However, in my opinion, putting the notify_one before unlock causes the operations of notify->unlock->the other thread acquires the lock, wile putting the notify_one after unlock causes the operations of unlock->notify->the other thread acquires the lock. What is the difference here?</li>
  </ol>