Hard
Checking a condition variable's predicate outside the mutex
This is a different bug from the classic spurious-wakeup issue (where cv.wait can return without any notify at all, fixed by looping/re-checking the predicate). Here the predicate check and the wait() call are correctly using while-style re-checking, but the check happens outside the mutex, as two separate steps. What can go wrong?
main.cpp
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void waiter() {
while (!ready) { // <-- read WITHOUT holding mtx
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock); // <-- separate step: re-lock, then wait
}
do_work();
}
void notifier() {
{ std::lock_guard<std::mutex> lock(mtx); ready = true; }
cv.notify_one();
}32 of 51 in Concurrency