Search code examples
c++c++11timecondition-variablesystem-clock

How do I deal with the system clock changing while waiting on a std::condition_variable?


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 (i.e., 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?


Solution

  • After considering the possible solutions to this problem, the one that seems to make the most sense is to ban the use of std::condition_variable (or at least make the caveat clear that it is always going to use the system clock). Then I have to basically re-implement the standard library's condition_variable myself, in a way that respects the clock choice.

    Since I have to support multiple platforms (Bionic, POSIX, Windows, and eventually MacOS), that means I'm going to maintain several versions of this code.

    While this is nasty, it seems like the alternatives are even nastier.