Search code examples
c++boosttimeoutcondition-variabletime-wait

What if the system time changes while I'm doing timed_wait with a duration?


When using timed_wait on a boost::condition_variable with a duration, will the wait condition time out after the duration even if the user (or ntp) changes the system time?

E.g.,

boost::posix_time::time_duration wait_duration(0, 0, 1, 0);  // 1 sec
// ** System time jumps back 15 minutes here. **
if( !signal.timed_wait(lock, wait_duration) )
{
    // Does this condition happen 1 second later, or about 15 minutes later?
}

Solution

  • As of the date of writing (Nov 2013), if the wall-clock time changes while you're waiting on a boost condition variable, you simply will get bad results.

    If you don't have to use boost, you can use what is called the "monotonic clock." Since the monotonic clock is unaffected by wall-clock time changes, it is not vulnerable to the problem you described. You can safely wait 5 seconds using the pthreads API using something like this:

    pthread_condattr_t attr;
    pthread_cond_t cond;
    struct timespec ts;
    
    pthread_condattr_init(&attr);
    pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
    pthread_cond_init(&cond, &attr);
    pthread_condattr_destroy(&attr);
    clock_gettime(CLOCK_MONOTONIC, &ts);
    ts.tv_sec += 5;
    pthreead_cond_timedwait(&cond, &mutex, &ts);
    

    You can check the implementation of boost::condition_variable. Maybe they will fix this some day. The implementation is here: http://svn.boost.org/svn/boost/trunk/boost/thread/pthread/condition_variable.hpp