The CPU runs a FED cycle on a stream of instructions, taken from the
executable
The OS is also a stream of instructions, performed on the CPU
The OS is responsible for interrupting one stream of instructions
(descheduling) and replacing it with another stream (scheduling)
Where’s the flaw here?
Who gets the CPU to execute the OS’ instruction stream so it can do
its job??
Switching Between Processes
One solution would be for the OS to act as an intermediate and
supervise the execution of each instructions, deciding when to start
executing its own code
Problem? Very slow…
We want each program to take full advantage of the CPU when it has a
chance to do so
Ideally, each process should get to execute its own instructions and
something should switch to the OS as necessary or appropriate
One way is to let the OS take control when a program requests I/O:
We block it, and let something else run, while hardware deals with the
I/O request
But what if a program doesn’t need to use I/O for a long time? Then
it just keeps running?
Cooperative Multitasking
Another solution: let the process relinquish control – yield the
CPU to the OS
This is called cooperative multitasking
Each program will run for a bit, and then say “okay, I can rest
for a bit” and pass control over to the OS, which can then schedule
another program
Where’s the downside?
What if programs don’t cooperate? What if they don’t relinquish
control of the CPU? What happens if…
while(1){}
This could be non-malicious
So we need a way of letting the OS take control without relying
on the programs to do that for us
Preemption
A more viable and robust solution is to ensure the OS has regular
say over what’s being executed by leveraging interrupts
Mechanism: Exceptional
Control Flow
There are 2 main categories of exceptions
Asynchronous: (Hardware) Interrupts
Caused by external events (external to the CPU) - meaning not caused
by something the software did
Examples: timer interrupts, Ctrl+C, data available from disk, data
arrives from net, …
Synchronous
Traps
Intentionally triggered by the software - system calls,
breakpoints
System calls are the primary mechanism of how user programs can
interact with the OS
Used to request a service from the OS - The service code needs to
execute in privileged mode