Home / Learn Embedded C / Context Switching Explained
Context Switching Explained
How the scheduler saves one task's state and restores another's when switching between them.
How to think about this
In plain terms
A context switch saves the currently-running task's complete execution state (registers, stack pointer, program counter) into its own saved storage, then loads a different task's previously-saved state, resuming it exactly where it left off.
Why we use it
This is what makes multitasking on a single CPU core possible at all — each task genuinely believes it has the whole CPU to itself, with the context switch mechanism hiding the fact that many tasks are actually taking turns.
Under the hood
Context switching has a real, nonzero time cost (saving/restoring registers takes CPU cycles) — switching tasks far more often than necessary wastes CPU time purely on overhead rather than useful work, a consideration in scheduler/priority design.
Real-world use
- RTOS scheduler internals
- Multitasking fundamentals
- Scheduling overhead analysis
Try it
Real context switching saves CPU registers, stack pointer and program counter; this saves a plain variable as a simplified stand-in for the same idea.
Try it: adding up context-switch overhead over many switches
Each individual switch is cheap, but switching unnecessarily often adds up to real wasted CPU time across a full second.
Quick quiz
1. What does a context switch actually do?
A context switch is precisely the save-and-restore mechanism that lets the scheduler pause one task and resume a different one, each unaware of the other's existence.