Question

I heard that some unix implementations use alarm(2) to implement sleep function. If it is true, I guess following code might not safe because SIGALRM may be sent to process, which is received by root thread.

#include <pthread.h>
#include <unistd.h>

void *doit(void *arg) {
    sleep(1);
    return NULL;
}

int main(int argc, char *argv[]) {
    pthread_t th;

    pthread_create(&th, NULL, doit, NULL);
    sleep(5);
    pthread_join(th, NULL);
    return 0;
}

Is it safe to call sleep(3), usleep(3) or nanosleep(2) in thread?

No correct solution

OTHER TIPS

I'm not completely sure if those functions aren't thread safe but in my experience I recommend you using the Thread sleep functions which are defined in the header thread. In the last multithreading application I developed, in some executions I had some random errors. They completely stopped when I started using the specific functions for threads. These functions are:

  • std::this_thread::sleep_for: which makes the thread sleep for at least (due to thread scheduling it could be longer) the time given. Ex:
this_thread::sleep_for(chrono::milliseconds(sleepTime));

void sleep_for(const std::chrono::duration<Rep, Period>& sleep_duration);
  • std::this_thread::sleep_until: which makes the thread sleep until the time point is reached (due to thread scheduling it could be longer too). Ex:
    this_thread::sleep_until(chrono::system_clock::time_point timePoint);
    
    void sleep_until(const std::chrono::time_point<Clock,Duration>& sleep_time);

If I'm not mistaken the only real difference between both is the definition of the sleep time. And I think you can only use integers for sleepTime, I remember having compilation errors when I tried to use a float and chrono::seconds.

I don't know what's your purpose to use sleep() in a thread, but I never recommend others to do so. If you want to measure a certain time, you can use application timer. For example, if you want to control running order of all the threads, you can use pthread_cond. Linux also provides many ways to allow you to sync threads.

Have a quick look of "man 3 sleep", which give the following answers. " BUGS sleep() may be implemented using SIGALRM; mixing calls to alarm(2) and sleep() is a bad idea. Using longjmp(3) from a signal handler or modifying the handling of SIGALRM while sleeping will cause undefined results.

Compared to sleep(3) and usleep(3), nanosleep() has the following advantages: it provides a higher resolution for specifying the sleep interval; POSIX.1 explicitly specifies that it does not interact with signals; and it makes the task of resuming a sleep that has been interrupted by a signal handler easier. "

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top