why does an infinite loop of the unintended kind i

2019-04-05 15:02发布

问题:

I know an infinite loop to the unintended kind usually causes a high CPU usage. But, I don't quite understand why. Can anyone explain that to me?

回答1:

The CPU cannot do anything else while it's executing that loop (which never ends). Even if you're using a pre-emptive multi-tasking system (so that infinite loop will only clog forever its own process or thread), the loop will "eat" its time slice each time the OS's pre-emptive scheduler hands it the CPU for the next slice -- doing nothing, but eating up one slice's worth of CPU time each and every time, so that much CPU is lost to all other threads which could otherwise be doing useful work.



回答2:

Infinite loops are no different than any other code running. The computer doesn't know that the infinite loop isn't a complicated calculation that just requires a lot of iterations.

Unless the infinite loop contains code that calls some system functions that yield time back to the OS, the OS treats it as a process that is actively working on something and gives it time to execute. If no other processes are running, it will eat up 100% of the CPU (on a single core system).



回答3:

Infinite loops in themselves aren't a problem at all. Most applications that interact with a user are infinite loops. They repeatedly wait for user, act on it, and perform the cycle again. The operating system itself is an infinite loop. These kinds of infinite loop are said to be 'productive' because despite repeating something indefinitely, they periodically output something useful to the user.

I guess your concern is with unproductive infinite loops. But it's clear why these are a problem. They have all of the disadvantages of productive loops (consume power, use CPU time and so on) with none of the advantages ie. they don't produce anything useful.



回答4:

You are probably referring to the Halt and Catch Fire instruction