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.

Quick summaryHow 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

Simulating saving and restoring a task's "context" (just a couple of values here)C: edit and run

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

Accumulating the time cost of frequent context switchesC: edit and run

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?