0

Let's say that we are writing a C program that calls the sleep() function. For instance, by calling sleep(7), the calling thread would be put to sleep for 7 seconds.

My question is: Will the thread awake after 7 seconds of our time/clock, or it could take longer, given the fact that each process has its own quantum time on the CPU, because there are many processes running consecutively?

  • 1
    It will be woken not earlier than 7 seconds of wall clock later. That might be in almost exactly 7 seconds, or (if lots of higher priority processes come in between) later, even much later. – vonbrand Jan 16 '16 at 0:01
  • 1
    @vonbrand, no that's simply not true. Please read (both) answers for a reason why – roaima Jan 16 '16 at 18:37
5

The definition of sleep(3) allows for the call to return before, at, or after the time specified:

DESCRIPTION sleep() makes the calling thread sleep until seconds seconds have elapsed or a signal arrives which is not ignored.

So we have these possible scenarios

  1. The call is interrupted with an uncaught signal. sleep() returns immediately and before the specified time
  2. The call completes satisfactorily, but the system is so busy it can't schedule your task for some time
  3. The call complete satisfactorily and is put back on the run queue and executed immediately
2

POSIX guarantees you that a successful, uninterrupted sleep will sleep at for least as long as you request:

http://pubs.opengroup.org/onlinepubs/009604599/functions/sleep.html

On Linux, it may take longer due to 1) rounding 2) waiting on the scheduler to put the process/thread on the CPU 3) time spent in a stopped state: http://man7.org/linux/man-pages/man2/nanosleep.2.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.