4 ms·
A very interesting article. But the real punchline is the very last sentence: > I wonder why there is even a returned status at all if you cannot rely on it.
by quietbritishjim 6y ago
A very interesting article. But the real punchline is the very last sentence:
> I wonder why there is even a returned status at all if you cannot rely on it.
With a normal untimed condition variable, we are taught to check for spurious wakeups. So not:
// Bad
Mutex.lock();
if (!itemReady) {
Cond.wait();
}
DoStuff();
But instead:
// Good
Mutex.lock();
while (!itemReady) {
Cond.wait();
}
DoStuff();
And so it goes with a timed condition variable. The return value is irrelevant. Instead, manually inspect the situation:
* Is the condition you're waiting for satisfied e.g. with queue non-empty? If so, great, use it! (There's a tiny chance of race condition here, where the timer expired after the item was issued on the queue but before the condition variable was signalled. But that absolutely doesn't matter.)
* Otherwise, recheck the time since you started waiting. Is the time now greater than the deadline? If so, you've timed out.
* Otherwise, it was a spurious wakeup. Go back to sleep with the same deadline (i.e. shorter wait period) as before.
If you do that in your code then the race described in the article won't affect you.