Context Switching Explained

Switching the CPU From One Process to Another

A context switch is the process of saving the currently running process's state and loading a different process's previously saved state, so the CPU can resume executing that other process exactly where it had left off.

The Steps of a Context Switch

1. Save Process A's current CPU registers and program counter into Process A's PCB
2. Update Process A's state (e.g. to Ready or Waiting)
3. Select the next process to run (Process B) - this is the scheduler's job
4. Load Process B's saved registers and program counter from Process B's PCB
5. Resume execution - now running Process B, exactly where it left off

This is exactly why the PCB, covered in the previous note, matters so much: it's precisely what makes steps 1 and 4 possible - without a place to save and restore this exact information, a switch like this couldn't happen reliably at all.

Why Context Switching Isn't Free

Saving and restoring registers, updating memory management structures, and potentially invalidating CPU caches all take real time - time during which neither Process A nor Process B is actually making forward progress. This overhead is a genuine cost the OS must account for when deciding how frequently to switch between processes.

Why Switching Too Often Can Hurt Performance

Switching processes very frequently gives better responsiveness (each process gets the CPU sooner), but wastes more total time on context-switch overhead itself. Switching less frequently reduces that overhead, but can make the system feel less responsive - a genuine trade-off that scheduling algorithms (covered later in this section) must balance.

What Actually Triggers a Context Switch

  • A running process's allotted time slice expires.
  • A running process voluntarily blocks, waiting for I/O.
  • A higher-priority process becomes ready to run.
  • An interrupt occurs that requires immediate attention.
Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.