I am just interested how sleep(time in ms)
is implemented in a C library or basically at the OS level...
I am guessing...
Any clues? Probably C library source code can explain? I am not too particular about how "C" is implementing it... I am just wondering in general how the "sleep()" function is implemented.
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.
/bin/sleep is Linux or Unix command to delay for a specified amount of time. You can suspend the calling shell script for a specified time. For example, pause for 10 seconds or stop execution for 2 mintues. In other words, the sleep command pauses the execution on the next shell command for a given time.
The concept of sleep and wake is very simple. If the critical section is not empty then the process will go and sleep. It will be waked up by the other process which is currently executing inside the critical section so that the process can get inside the critical section.
Difference between wait() and sleep() The major difference is that wait() releases the lock while sleep() doesn't release any lock while waiting. wait() is used for inter-thread communication while sleep() is used to introduce a pause on execution, generally.
Sleep()
is implemented at the OS level. The processor doesn't spin when a task/thread/process is sleeping. That particular thread is put on a pending queue (the thread isn't ready to run) until the time has expired at which point the thread will be placed on the ready to run queue.
In the meantime, other threads that are ready to run will be run.
Only if no threads are ready to run will the OS go into the idle thread, which in generally issues instructions to shutdown (or put into a low-power state anyway) the processor until an hardware interrupt occurs.
Only for a very simple system (like the most simple of embedded systems), might Sleep()
actually be implemented as nothing more than a busy wait loop.
Any operating system textbook, such as "Modern Operating Systems" by Tanenbaum will cover this in great detail - pretty much any of them (even an old, cheap, used one).
The answer to your question is completely operating-system and implementation-dependent.
A simple way to think about it: When you call sleep()
, the OS calculates the wakeup time, then sticks your process on a priority queue somewhere. It then just doesn't schedule your process to get any execution time until enough real time has passed for it to get popped off the queue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With