How does the OS scheduler regain control of CPU?

Edwin Dalorzo picture Edwin Dalorzo · Jul 13, 2012 · Viewed 10.5k times · Source

I recently started to learn how the CPU and the operating system works, and I am bit confused about the operation of a single-CPU machine with an operating system that provides multitasking.

As such, supposing my machine has a single CPU, this would mean that, at any given time, only one process could be running.

Now, I can only assume that the scheduler used by the operating system to control the access to the precious CPU time is also a process.

Thus, in this machine, either the user process or the scheduling system process is running at any given point in time, but not both.

So here's a question:

Once the scheduler gives up control of the CPU to another process, how can it regain CPU time to run itself again to do its scheduling work? I mean, if any given process currently running does not relinquish (yield) the CPU, how could the scheduler itself ever run again and ensure proper multitasking?

So far, I had been thinking, well, if the user process requests an I/O operation through a system call, then in the system call we could ensure the scheduler is allocated some CPU time again. But I am not even sure if this works in this way.

On the other hand, if the user process in question were inherently CPU-bound, then, from this point of view, it could run forever, never letting other processes, not even the scheduler run again.

Supposing a time-sliced scheduling, I have no idea how the scheduler could slice the time for the execution of another process, when it is not even running?

I would really appreciate any insight or references that you can provide in this regard.

Answer

usr picture usr · Jul 13, 2012

The OS sets up a hardware timer (Programmable interval timer or PIT) that generates an interrupt every N milliseconds. That interrupt is delivered to the kernel and user-code is interrupted.

It works like any other hardware interrupt. For example your disk will force a switch to the kernel when it has completed an IO.