Context Switching
A context switch is a controlled save-and-restore. It makes multitasking possible, but it is pure overhead: no user work happens during the switch.
In plain English
A context switch is putting a book down with a bookmark and picking up another.
By the end you will be able to
- List the steps of a context switch.
- Explain what is saved and what is restored.
- Distinguish a direct switch from a switch caused by an interrupt.
- Describe why frequent switches reduce throughput.
The switch sequence
The kernel saves the running process's registers, program counter, and stack pointer into its PCB. It updates the process state, chooses another process, and restores that process's registers and program counter from its PCB. If the processes have different address spaces, the kernel also switches the page table or memory map. Then execution resumes in the new process.
save_context(old_process);
old_process.state = READY;
new_process = scheduler_pick();
new_process.state = RUNNING;
restore_context(new_process);
switch_address_space(new_process);Interrupt-driven switches
A timer interrupt or a blocking system call gives the kernel a reason to switch. The interrupt path already saves some state; the scheduler may then decide to run a different process. A voluntary switch happens when the running process blocks. An involuntary switch happens when the scheduler preempts it. Both use the same PCB save/restore mechanism.
The cost
A context switch costs CPU cycles and cache locality. Saving and restoring registers is small compared with the indirect cost: the new process's working set may not be in cache, and the TLB may need to be flushed or tagged. If the time quantum is too small, the system spends too much time switching and too little time doing useful work.
Key takeaways
- A context switch saves one PCB and restores another.
- The address space may also need to change.
- Switches can be voluntary (blocking) or involuntary (preemption).
- The cost is more than register saves: cache and TLB locality suffer.
- Too many switches reduce throughput.
Common pitfalls
- Thinking a context switch is free because registers are fast.
- Forgetting to switch the memory map when address spaces differ.
- Assuming every interrupt causes a context switch; the scheduler decides.
Kernel notes
- List the save, choose, restore, and address-space steps.
- Explain the direct and indirect costs.
- Relate quantum size to switch overhead.
Quick check
1. What is saved during a context switch?
2. Why can a very small time quantum reduce throughput?