This might be a stupid question, but how do sleep(), wait(), pause(), functions work?
sleep()
wait()
pause()
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.
sleep
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.
wakeMeUpWhen
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.
1.4m articles
1.4m replys
5 comments
57.0k users