How is sleep implemented at the OS level?

FatDaemon picture FatDaemon · Nov 12, 2009 · Viewed 14k times · Source

I am just interested how sleep(time in ms) is implemented in a C library or basically at the OS level...

I am guessing...

  1. May be the based on the processor speed you do a while loop of nop's (I am not sure if the sleep time will be accurate)...
  2. Any special register in processor, where you write some value and the processor simply halts for specified time (this would be very inefficient as the processor can't run even other programs).

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.

Answer

Michael Burr picture Michael Burr · Nov 12, 2009

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).