Can this_thread::sleep() be interrupted on linux?

Issue

When using nanosleep, we need to check the return value to detect whether we have been interrupted by a signal:

while ((nanosleep(&rqtp, &rmtp) == -1) && (errno == EINTR))
{
    if (rmtp.tv_nsec != 0 || rmtp.tv_sec != 0)
    {
        rqtp = rmtp;
        continue; /* Wait again when interrupted by a signal handler */
    }
}

I want to use std::this_thread::sleep_for() instead of nanosleep(). Is it possible that a call to this_thread::sleep_for() is also interrupted (ends earlier as specified)?

Solution

If you use GCC’s libstdc++, you can find the corresponding code here:

while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR)
      { }

with the timespec __ts prepared accordingly. So it basically does the same thing as your code loop and restarts the sleep after a signal interrupt.

The C++ standard itself says:

The functions whose names end in _­for take an argument that specifies
a duration. These functions produce relative timeouts.
Implementations should use a steady clock to measure time for these
functions. Given a duration argument Dt, the real-time duration of
the timeout is Dt+Di+Dm.

Where Di and Dm are delays introduced by the implementation and by the resource management, as described in the previous sentence of the standard. Assuming that these delays are positive (which they should be), the sleep time is always at least as long as the specified time.

Thus in my opinion, the standard guarantees that the sleep does not end early.

Answered By – Jakob Stark

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published