Skip to content
UniCircle
EasyConceptualProcess management

What happens during a context switch and why is it expensive?

Question OS-101

Walk me through what the operating system actually does during a context switch. Why do we say context switches are expensive, and is switching between two threads of the same process cheaper than switching between two processes?

Show hints

Think about what the CPU must forget and what it must remember about the old task.

Show the explanation

Model answer. A context switch is the kernel stopping one running task and resuming another on the same CPU core.

Steps

  • Something triggers kernel entry: a timer interrupt (preemption), a blocking system call such as a disk read, or the task voluntarily yielding.
  • The kernel saves the current task's CPU state — program counter, stack pointer, general-purpose registers, flags — into its process control block (PCB) or thread control block.
  • The scheduler picks the next ready task.
  • If the next task belongs to a different process, the kernel switches the address space by loading that process's page-table base (for example, CR3 on x86).
  • It restores the saved registers of the new task and returns to user mode, where execution continues exactly where that task left off.

Why it is costly

  • It is pure overhead: no user work is done while switching.
  • Changing address spaces can invalidate TLB entries (unless the hardware tags entries with address-space IDs), so the new task suffers TLB misses.
  • CPU caches are "cold" for the new task, so it takes extra memory accesses before it runs at full speed. This indirect cost often exceeds the direct cost of saving registers.

Threads vs processes
Threads of the same process share one address space, so a thread switch skips the page-table change and keeps the TLB and much of the cache useful. It is therefore usually cheaper than a process switch, though registers and the stack pointer must still be swapped.

Common follow-up: "Is a system call a context switch?" Not necessarily — a system call is a mode switch (user to kernel and back) for the same task. A context switch happens only if the kernel decides to run a different task before returning.

Original UniCircle question. Last reviewed 28 Oct 2026.