const auto duration = Returns_10_seconds ();
while (cv.wait_for (lock, duration) == std :: cv_status :: timeout);
This is definitely the wrong thing, and therefore it makes no sense to discuss how to fix it for the case of false awakenings, as it is violated even for ordinary awakenings, since the waiting condition is not reviewed after returning from the wait. Strike>
const auto duration = Returns_10_seconds(); while(!Predicate()) cv.wait_for(lock, duration);
Even after editing, the answer remains unchanged: you cannot handle the “false awakenings” because you cannot really explain the reason for the awakening - it is quite possible that it will be completely legal awakening due to a call before condition_variable::notifyXXX before the timeout expires.
First, note that you cannot distinguish between waking up caused by calling condition_variable::notifyXXX and waking up caused, for example, by a POSIX signal [1]. Secondly, even if the POSIX signals are not disturbing, the waiting thread should still review the condition, since it is possible for the condition to change between the time when the status signaling is signaled and the waiting thread returns from the waiting condition.
What you really need to do is handle it in a special way, not waking up before a timeout, but waking up due to a timeout. And it completely depends on the reasons for having a timeout in the first place, i.e. From the specifics of the application area / problems.
[1] if the wait on the condition variable is interrupted by a signal, after the thread handler is executed, the thread is allowed to either resume the wait or return
source share