Search code examples
c++multithreadingc++11condition-variable

What is the difference between std::condition_variable::wait_for and std::condition_variable::wait_until?


The reference I'm using explains the two in the following way:

  • wait_for "blocks the current thread until the condition variable is woken up or after the specified timeout duration"

  • wait_until "blocks the current thread until the condition variable is woken up or until specified time point has been reached"

What is the difference? Will wait_until spin so that the thread can continue exactly (more or less) when it is signaled, whereas wait_for just adds the thread back into scheduling at that point?


Solution

  • The difference is in how the wait duration is represented: wait_for takes a relative time ("wait for up to 10 seconds"), whereas wait_until takes an absolute time ("wait until 12:00 on October 30, 2012").

    Compare the declarations of the time parameters:

    // wait_for:
    const std::chrono::duration<Rep, Period>& rel_time
    
    // wait_until:
    const std::chrono::time_point<Clock, Duration>& abs_time