user342673
user342673

Reputation: 674

why does an infinite loop of the unintended kind increase the CPU use?

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?

Upvotes: 12

Views: 9542

Answers (4)

dar7yl
dar7yl

Reputation: 3747

You are probably referring to the Halt and Catch Fire instruction

Upvotes: 0

Dan Piponi
Dan Piponi

Reputation: 8116

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.

Upvotes: 6

Alex Martelli
Alex Martelli

Reputation: 881675

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.

Upvotes: 20

Ecton
Ecton

Reputation: 10722

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

Upvotes: 8

Related Questions