Search code examples
multithreadingoperating-systemcpu

Why doesn't an infite loop lock an OS?


Say you had a process running some code that looked like this

while (true) {
  //do nothing
}

Why doesn't this block the OS?

I know that operating systems have a process scheduler (such as CFS on Linux), but how does this actually work?

If code is executing an infinite loop, when does a process scheduler have time to execute its own code?

Wouldn't there need to be something external running that interrupts the running code to yield back to the OS? If so, how does an OS like Linux manage this?

Do CPUs have built-in functionality to manage use-cases like this?


Solution

  • First thing to understand here is that an operating system is always in control, and it is fully capable of interrupting any process at any time. CPU's also provide hardware support to achieve this.

    Most of the contemporary operating systems(including Linux) schedulers can interrupt an executing process. its usually done by using a timer interrupt. its essentially a programmable clock, where you can define what happens on every clock tick.

    In Linux the process preemption by scheduler can be defined in following steps

    1. CPU local timer interrupt is invoked and the interrupt handler starts executing
    2. Now interrupt handler is in control of CPU (so your infinite loop code is in paused state)
    3. interrupt handler checks if current process should continue to execute (Check priority, time quanta etc)
    4. If the process cant be allowed to execute then its preempted and a new process is assigned the CPU

    So as you can see any process is never given 100% control of the system and an operating system always have means to stop or kill it.