Appearance
4. Context Switching
When the CPU switches from one process/thread to another, it must save the current state and load the new one — this is the context switch.
What's saved/restored: PC, registers, stack pointer, CPU flags — into/from the PCB.
Step by step:
- Timer interrupt fires (or process blocks on I/O)
- CPU switches to kernel mode
- OS saves the current process's context into its PCB
- Scheduler picks the next process
- OS loads that process's context from its PCB
- CPU switches back to user mode
- New process resumes where it left off
Why it's expensive: direct costs are saving/restoring registers and switching page tables (TLB flush). The bigger, indirect cost: the TLB and CPU caches go cold — the new process suffers a burst of cache misses while they warm back up. A raw switch takes 1–10 µs, but the cache-warmup penalty afterward can be 10–100× more expensive.
| Aspect Process Switch Thread Switch | ||
|---|---|---|
| Save/restore | Full PCB | Registers + stack + PC only |
| Memory map | Must switch (TLB flush) | No switch (same address space) |
| Cost | Heavy | Light |
| Cache impact | High | Low |
Triggers: timer interrupt, I/O block, system call, preemption by a higher-priority process, voluntary yield.
Analogy: solving a math problem, boss interrupts you for another task — you bookmark your page and note where you were (save context), switch tasks, then later read your notes and resume exactly where you left off.