Is there a way to express: “Listen, I really only have two seconds. MyPredicate () is still false at this time and / or the lock is still locked, I don’t care, just go on no matter ...”
Yes, there is a way, but, unfortunately, in the case of wait_for it must be manual. wait_for waits indefinitely due to Spurious Wakeup . Imagine your loop as follows:
while(!myPredicate()) cv.wait_for(lock, std::chrono::duration::seconds(2);
Fake awakening can happen at any time on an arbitrary platform. Imagine that in your case this happens within 200 ms. In this regard, without any external notification of wait_for() , awakening and checking for myPredicate() in the loop condition will occur.
As expected, the condition will be false, so the loop will be true, and again it will execute cv.wait_for(..) with a fresh 2 seconds. So it will work endlessly.
Either you control this update duration yourself, or use wait_until() , which is ultimately called in wait_for() .
iammilind
source share