Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does sleep() work?

Tags:

This might be a stupid question, but how do sleep(), wait(), pause(), functions work?

like image 634
Blender Avatar asked Feb 06 '11 05:02

Blender


People also ask

How does sleep () actually work?

sleep() causes the calling thread to be removed from of the Operating System's ready queue and inserted into another queue where the OS periodically checks if the sleep() has timed out, after which the thread is readied again.

How does sleep in Linux work?

sleep command is used to create a dummy job. A dummy job helps in delaying the execution. It takes time in seconds by default but a small suffix(s, m, h, d) can be added at the end to convert it into any other format. This command pauses the execution for an amount of time which is defined by NUMBER.

What triggers sleep?

But when darkness comes at night, the SCN sends messages to the pineal gland. This gland triggers the release of the chemical melatonin. Melatonin makes you feel sleepy and ready for bed.


1 Answers

We can see the sleeping operation from a more abstract point of view: it is an operation that let you wait for an event.
The event in question is triggered when the time passed from sleep invocation exceeds the sleep parameter.

When a process is active (ie: it owns a CPU) it can wait for an event in an active or in a passive way:

  • An active wait is when a process actively/explicitly waits for the event:

    sleep( t ):     while not [event: elapsedTime > t ]:         NOP // no operatior - do nothing 

    This is a trivial algorithm and can be implemented wherever in a portable way, but has the issue that while your process is actively waiting it still owns the CPU, wasting it (since your process doesn't really need the CPU, while other tasks could need it).

    Usually this should be done only by those process that cannot passively wait (see the point below).

  • A passive wait instead is done by asking to something else to wake you up when the event happens, and suspending yourself (ie: releasing the CPU):

    sleep( t ):     system.wakeMeUpWhen( [event: elapsedTime > t ] )     release CPU 

    In order to implement a passive wait you need some external support: you must be able to release your CPU and to ask somebody else to wake you up when the event happens.

    This could be not possible on single-task devices (like many embedded devices) unless the hardware provides a wakeMeUpWhen operation, since there's nobody to release the CPU to or to ask to been waken up.

    x86 processors (and most others) offer a HLT operation that lets the CPU sleep until an external interrupt is triggered. This way also operating system kernels can sleep in order to keep the CPU cool.

like image 133
peoro Avatar answered Dec 30 '22 06:12

peoro