Search code examples
c++c++11stlsleepthread-sleep

Can std::this_thread::sleep_for() have spurious wakeups?


Note, this is not a question about std::condition_variable::wait_for(). I know that can wake spuriously.

My program’s behavior suggests the answer to this question is Yes, but the STL documentation is quite clear for the condition_variable case. At least at cppreference.com, the correct answer for this_thread appears to be No.

Compiler is gcc 4.8.1, in case this is a defect.


Solution

  • The relevant sections of the C++ Standard (paragraphs [thread.thread.this]/7-9) do not mention anything about spurious wake-ups for std::this_thread::sleep_for, unlike e.g. for std::condition_variable::wait_for.

    template <class Rep, class Period>
    void sleep_for(const chrono::duration<Rep, Period>& rel_time);
    

    7 Effects: Blocks the calling thread for the relative timeout (30.2.4) specified by rel_time.

    8 Synchronization: None.

    9 Throws: Timeout-related exceptions (30.2.4).

    This implies that the behavior you are observing is non-conforming.