Why does an empty loop use so much processor time?

前端 未结 12 2511
小鲜肉
小鲜肉 2021-02-13 15:05

If I have an empty while loop in my code such as:

while(true);

It will drive the processor usage up to about 25%. However if I do the followin

12条回答
  •  野的像风
    2021-02-13 15:35

    Basically, you've got several "process scheduler" states. I'll name three of them. One: Ready Two: Running Three: Blocked

    These states / queues only exist because of the limited number of cores on your processor. In Ready, processes are scheduled that are totally ready for execution. They don't have to wait for input, time, or whatever. On Running, processes actually "have" the processor and thus ARE running. State Blocked means your process is waiting for an event to happen before queueing for the processor.

    When you keep on testing for while(true) you keep your process in the "ready" queue. Your process scheduler gives it a certain amount of time, and after a while, removes it from the processor (placing it on the back of the "ready" queue). And thus your process will keep coming back "on" the processor, keeping it busy.

    When you execute a "sleep" statement, your process will not be scheduled on process until the prerequisity is fulfilled - in this particular case, as long as the time passed after the "sleep" command <= 1000 ms.

提交回复
热议问题