Medium
Guarding condition_variable::wait with if instead of while
waiter() runs on one thread, notifier() eventually runs on another. What's wrong (if anything) with guarding cv.wait(lock) with if instead of while?
main.cpp
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void waiter() {
std::unique_lock<std::mutex> lock(mtx);
if (!ready) { // <-- if, not while
cv.wait(lock);
}
do_work(); // assumes ready == true
}
void notifier() {
{ std::lock_guard<std::mutex> lock(mtx); ready = true; }
cv.notify_one();
}8 of 51 in Concurrency