Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can preemptive multitasking work, when OS is just one of the processes?

I am now reading materials about preemptive multitasking - and one thing escapes me.

All of the materials imply, that operating system somehow interrupts the running processes on the CPU from the "outside", therefore causing context switching and the like.

However, I can't imagine how would that work, when operating system's kernel is just another process on the CPU. When another process is already occuping the CPU, how can the OS cause the switch from the "outside"?

like image 621
Karel Bílek Avatar asked Dec 07 '22 19:12

Karel Bílek


2 Answers

The OS is not just another process. The OS controls the behavior of the system when an interrupt occurs.

Before the scheduler starts a process, it arranges for a timer interrupt to be sent when the timeslice ends. Assuming nothing else happens before then, the timer will fire, and the kernel will take over control. If it elects to schedule a different process, it will switch things out to allow the other process to run and then return from the interrupt.

like image 91
David Schwartz Avatar answered Jan 18 '23 14:01

David Schwartz


Hardware can signal the processor - this is called an "interrupt" - and when it occurs, control is transferred to the kernel (regardless of which process was executing at the time). This function is built in to the processor. Specifically, control is transferred to an "interrupt handler" which is a function/method within the kernel.The kernel can schedule a timer interrupt, for instance, so that this happens periodically. Once an interrupt occurs and control is transferred to the kernel, the kernel can pass control back to the originally executing process, or another process that is scheduled.

like image 42
davmac Avatar answered Jan 18 '23 16:01

davmac