As it turns out, condition_variable::wait_for
should really be called condition_variable::wait_for_or_possibly_indefinitely_longer_than
, because it needs to reacquire the lock before really timing out and returning.
See this program for a demonstration.
Is there a way to express, "Look, I really only have two seconds. If myPredicate()
is still false at that time and/or the lock is still locked, I don't care, just carry on regardless and give me a way to detect that."
Something like:
bool myPredicate();
auto sec = std::chrono::seconds(1);
bool pred;
std::condition_variable::cv_status timedOut;
std::tie( pred, timedOut ) =
cv.really_wait_for_no_longer_than( lck, 2*sec, myPredicate );
if( lck.owns_lock() ) {
// Can use mutexed resource.
// ...
lck.unlock();
} else {
// Cannot use mutexed resource. Deal with it.
};
wait_until
suffers from the same "feature". "Once notified or once it isabs_time
, the function unblocks and callslck.lock()
, leavinglck
in the same state as when the function was called. Then the function returns (notice that this last mutex locking may block again the thread before returning)." – Trepang