Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 214
user342673 Avatar asked May 17 '10 00:05

user342673


People also ask

What happens when you run an infinite loop?

What are infinite loops? An infinite loop is a piece of code that keeps running forever as the terminating condition is never reached. An infinite loop can crash your program or browser and freeze your computer.

Why would an infinite loop be used?

Usually, an infinite loop results from a programming error - for example, where the conditions for exit are incorrectly written. Intentional uses for infinite loops include programs that are supposed to run continuously, such as product demo s or in programming for embedded system s.

How does the CPU stops a program from going into an infinite loop?

Probable answer is, the CPU won't crash and other processes can execute in the CPU as because every process has a specific time slice, so after the time slice of P1 expires, other waiting processes can gain the CPU.

Can infinite loop damage your computer?

So no, an infinite loop will not wear out your cpu or ram, but it could prevent some parts of them from entering low power modes, depending on the actual hardware an OS. Save this answer.


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

like image 176
Alex Martelli Avatar answered Oct 21 '22 07:10

Alex Martelli