Below is some code example about C++ condition variable from CPPConference.com:
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<std::mutex> lk(m);
cv.wait(lk, []{return ready;});
// after the wait, we own the lock.
std::cout << "Worker thread is processing data\n";
data += " after processing";
// Send data back to main()
processed = true;
std::cout << "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();
}
I do not quite understand the part at the end where the lock is released before the other thread is notified.
- Does it work if the code put cv.notify_one() before lk.unlock()?
- Why is it a better practice to put cv.notify_one() after lk.unlock()? According to this page, "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?