title: What's the algorithm behind sleep()?
body: <p>Now there's something I always wondered: how is sleep() implemented ?</p>
  
  <p>If it is all about using an API from the OS, then how is the API made ?</p>
  
  <p>Does it all boil down to using special machine-code on the CPU ? Does that CPU need a special co-processor or other gizmo without which you can't have sleep() ?</p>
  
  <p>The best known incarnation of sleep() is in C (to be more accurate, in the libraries that come with C compilers, such as GNU's libc), although almost every language today has its equivalent, but the implementation of sleep in some languages (think Bash) is not what we're looking at in this question...</p>
  
  <p>EDIT: After reading some of the answers, I see that the process is placed in a wait queue. From there, I can guess two alternatives, either</p>
  
  <ol>
  <li>a timer is set so that the kernel wakes the process at the due time, or</li>
  <li>whenever the kernel is allowed a time slice, it polls the clock to check whether it's time to wake a process.</li>
  </ol>
  
  <p>The answers only mention alternative 1. Therefore, I ask: how does this timer behave ? If it's a simple interrupt to make the kernel wake the process, how can the kernel ask the timer to "wake me up in 140 milliseconds so I can put the process in running state" ?</p>