Why must a wait on a std::condition_variable be wrapped in a predicate loop?
Correct answer
B. Wake-ups can occur without a notify, so the condition must be rechecked
16 views
B. Wake-ups can occur without a notify, so the condition must be rechecked
16 views
condition_variable waits may return spuriously, without any corresponding notify, so the predicate has to be re-evaluated in a loop; the overload taking a predicate does this for you. The mutex must also be held while the predicate is checked, to close the window in which a notify could be lost between the test and the sleep. A notification issued with no waiter is simply not remembered, which is why the state, not the signal, must be the thing that is checked.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is B? Ask here and get an explanation.