What's the algorithm behind sleep()?

后端 未结 8 1898
灰色年华
灰色年华 2020-12-07 16:36

Now there\'s something I always wondered: how is sleep() implemented ?

If it is all about using an API from the OS, then how is the API made ?

Does it all bo

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 17:21

    there's at least two different levels to answer this question. (and a lot of other things that get confused with it, i won't touch them)

    1. an application level, this is what the C library does. It's a simple OS call, it simply tells the OS not to give CPU time to this process until the time has passed. The OS has a queue of suspended applications, and some info about what are they waiting for (usually either time, or some data to appear somewhere).

    2. kernel level. when the OS doesn't have anything to do right now, it executes a 'hlt' instruction. this instruction doesn't do anything, but it never finishes by itself. Of course, a hardware interrupt is serviced normally. Put simply, the main loop of an OS looks like this (from very very far away):

      allow_interrupts ();
      while (true) {
        hlt;
        check_todo_queues ();
      }
      

      the interrupt handlers simpy add things to the todo queues. The real time clock is programmed to generate interrupts either periodically (at a fixed rate), or to some fixed time in the future when the next process wants to be awaken.

提交回复
热议问题