Skip to content

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:

  1. Timer interrupt fires (or process blocks on I/O)
  2. CPU switches to kernel mode
  3. OS saves the current process's context into its PCB
  4. Scheduler picks the next process
  5. OS loads that process's context from its PCB
  6. CPU switches back to user mode
  7. 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/restoreFull PCBRegisters + stack + PC only
Memory mapMust switch (TLB flush)No switch (same address space)
CostHeavyLight
Cache impactHighLow

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.