4

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"?

Karel Bílek
  • 36,467
  • 31
  • 94
  • 149

2 Answers2

8

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.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • A-ha, I think I start to get it. I didn't know it was possible to shedule a timer interrupt, I thought interrupting only happens with hardware access, that's what escaped me. Thanks! – Karel Bílek Sep 07 '11 at 03:16
7

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.

davmac
  • 20,150
  • 1
  • 40
  • 68
  • 1
    Oh! I knew what interrupt is, I just thought it happens only with hardware access and the like. So... if I am right, the kernel shedules a timer interrupt, that happens *periodically*, at the very start, gives itself as a interrupt handler and shedules the context switching *there*. Clever! :) – Karel Bílek Sep 07 '11 at 03:11
  • (I added the best answer to David Schwartz, because he got fewer points and I can't pick 2 best answers :)) – Karel Bílek Sep 07 '11 at 03:28