I'm trying to implement some cross-platform code in C++11. Part of this code implements a semaphore object using a std::condition_variable. When I need to do a timed wait on the semaphore, I use wait_until or wait_for.
The problem I'm experiencing is that it seems like the standard implementation of condition_variable on POSIX-based systems relies on the system clock, rather than the monotonic clock (see also: this issue against the POSIX spec)
That means that if the system clock gets changed to some time in the past, my condition variable will block for far longer than I expect it to. For instance, if I want my condition_variable to time out after 1 second, if someone adjusts the clock back 10 minutes during the wait, the condition_variable blocks for 10 minutes + 1 second. I've confirmed that this is the behavior on an Ubuntu 14.04 LTS system.
I need to rely on this timeout to be at least somewhat accurate (ie, It can be inaccurate within some margin of error, but still needs to execute if the system clock changes). It seems like what I'm going to need to do is write my own version of condition_variable that uses the POSIX functions and implements the same interface using the monotonic clock.
That sounds like A Lot Of Work - and kind of a mess. Is there some other way of working around this issue?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…