1
$\begingroup$

I know in theory how various scheduling algorithms work, such as round robin, where each process is given small time slices to run a few instructions, before the operating system passes execution onto the next process, and so on.

What I don't understand is how this is possible. The operating system is just some code, and so are all of the processes, so why doesn't this happen?

  1. OS passes execution to the first process.
  2. Now that process is running, the OS can't stop it, since the CPU can only run one instruction at a time, and that instruction is the process'.
  3. Now the operating system has no control over the process, and can't stop it.

Now obviously this doesn't happen, but why not? How would the operating system say something like "Okay, you can run 3 instructions now, but after that let the other process run"?

$\endgroup$
  • 1
    $\begingroup$ The simple answer is that the OS (or the scheduler specifically) is not "just some code", in the sense that it can treat itself differently from other processes to ensure that the scheduling is handled properly. How this works exactly is outside of my expertise, however. $\endgroup$ – Discrete lizard Apr 18 at 14:21
  • $\begingroup$ I understand that it can treat itself differently from other processes, but I don't understand how this is possible. Unless perhaps the CPU itself implements round-robin. $\endgroup$ – Jacob Garby Apr 18 at 14:23
  • 1
    $\begingroup$ Typically, the OS sets a hardware timer to trigger an interrupt periodically. When the interrupt is triggered, the scheduler can be invoked. $\endgroup$ – Pontus Apr 18 at 14:59
  • $\begingroup$ @Pontus thanks! That makes sense to me, if you put that in an answer I'd be happy to accept it, since that's about as much detail as I wanted. $\endgroup$ – Jacob Garby Apr 18 at 15:24
2
$\begingroup$

The operating system arranges for periodic timer interrupts, which only it can handle, so it periodically regains control of the CPU without requiring the co-operating of any other process. Also, when a process tries to access the hardware, that is mediated by the operating system, which gives it another opportunity to decide which process to run next.

$\endgroup$
  • 1
    $\begingroup$ About "accessing the hardware". This includes reading or writing files, receiving characters from a terminal... processes do "system calls" and, as many operations take some time, such as waiting until a character is received, or that a block is read form a disk, this gives the opportunity for the OS to schedule another task. $\endgroup$ – TEMLIB Apr 19 at 2:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.