Part 2 of 6 · 2 min read
The switch
In plain words: A reader marks the page in a book, closes it, and opens a second book at its own bookmark. Later, the first book is reopened at the right line. A context switch does the same with processes. The analogy stops at speed: a reader takes seconds, and the kernel takes about a microsecond, but a processor does thousands of instructions in that time.
The context of a process is the set of values the processor holds for it: the program counter, the other registers, and the pointers that say where its memory is. These values live in the processor while the process runs. To stop the process, the kernel copies them into the process's PCB (page 2). To start another process, it copies that process's saved values from its PCB into the processor.
The steps, for a switch from process A to process B:
| Step | What happens |
|---|---|
| 1 | An interrupt or a system call moves the processor to kernel mode (Level 0, page 5). Process A's state is saved by hardware and by the entry code, on the kernel's stack |
| 2 | The kernel decides that A must stop: its time slice is over, or it started to wait |
| 3 | The kernel saves A's registers in A's PCB and sets A's state to ready or waiting |
| 4 | The scheduler picks B |
| 5 | The kernel loads B's saved registers from B's PCB, and switches to B's address space |
| 6 | The kernel returns to user mode, and B continues exactly where it stopped |
Neither process notices. A's code simply resumes later with all registers as they were, and sees only that the clock has moved on.
During steps 3 to 5 the processor does no work for any user program. That is the overhead of switching. It is why the kernel does not switch every few instructions.
Context switch
A context switch is the operation by which the kernel stops the process that is running on a processor, saves its context in its process control block, and loads the saved context of another process so that the other process runs in its place.
Example: when a timer interrupt ends process A's time slice, the kernel saves A's registers, loads B's, and returns to B, which continues where it was last stopped.
Check yourself: 1. Where does the kernel save the context of the process that stops? 2. What does it load for the process that starts? 3. Why is the switch pure overhead?