Context Switching Between Processes
You'll learn what happens under the hood when the operating system switches the CPU from running one process to another.
What is Context Switching?
When the OS decides to pause one process and resume another, it must perform a context switch. Think of it like bookmarking your place in one book so you can read another—you need to remember exactly where you left off so you can continue later without confusion.
The "context" of a process is all the information needed to resume it: the values in CPU registers, the program counter (which instruction to execute next), stack pointers, and other state stored in the Process Control Block (PCB).
The Context Switch Mechanism
Here's what happens during a context switch:
- Save current process state: The OS stores all register values, program counter, and process state into the current process's PCB
- Update process state: Mark the old process as Ready or Waiting (it's no longer Running)
- Select next process: The scheduler chooses which process runs next
- Restore new process state: Load the selected process's saved register values and program counter from its PCB
- Update process state: Mark the new process as Running
- Resume execution: The CPU continues where the new process left off
The Overhead Cost
Context switching isn't free—it takes time (microseconds) during which no useful work is done. The CPU is busy saving and loading state instead of executing your program's instructions. Frequent context switches can noticeably slow down overall system performance, which is why the OS tries to balance responsiveness with efficiency.
Key Takeaway: Context switching is the essential but costly mechanism that allows multiple processes to share one CPU by saving and restoring complete process state through the PCB.