Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

c - How is sleep implemented at the OS level?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...