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?
4 Answers
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.

- 854,459
- 170
- 1,222
- 1,395
-
3This answer, although may be correct, looks too difficult and hence not much helpful to people asking this kind of questions. On top of extensive use of technical terms, the second sentence, which is most of the paragraph, is particularly way too long to parse. – sawa Oct 09 '12 at 20:36
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).

- 10,702
- 2
- 35
- 44
-
1Actually in modern general purpose O/S, any sane code will go into an interruptable wait state which stops the kernel from executing anything on that thread until it needs to. – L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳ May 17 '10 at 01:05
-
Agreed, but my comparison was with an intense calculation, such as ones done for academic research. – Ecton May 17 '10 at 22:00
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.

- 7,996
- 2
- 27
- 48
-
2Even though your first paragraph is informative and helpful, the second paragraph is circular. The question is, why do infinite loops of the unintended kind "consume power, use CPU time, and so on"? – sawa Oct 09 '12 at 20:33
-
Nowaday, you almost never need infinite loops to wait for user interactions. You generally use blocking OS or framework API and receive user input as events/callback. – XouDo Jun 25 '20 at 12:33