Interview Prep Zoneby CuriouserLabs

Question 2 of 5 · senior level

What happens during a context switch, and why do we say it's expensive?

🎤 Say this first

On a timer interrupt or block, the kernel saves the running thread's registers/PC into its task struct, picks the next thread (scheduler), restores its saved state, and — if it belongs to a different process — switches the address space (page-table base register). The direct cost is small (~1–10µs). The real cost is indirect: the new thread finds the CPU caches and TLB full of someone else's data, so it runs cold for a while. That's why 'more threads' beyond a point reduces throughput.

The full picture

🎬 What a context switch actually does

1 / 5
CPUrunning APC/regs = A's stateProcess A 🅰️RUNNINGPCB: (stale)Process B 🅱️READYPCB: PC, regs storedDirect cost: ~1–10µs of kernel work. Indirect cost: cache/TLB pollution — why too many threads hurts throughput.

Process A is running on the CPU: its program counter, registers and stack pointer live in CPU hardware. Process B sits in the ready queue, its state parked in its PCB (process control block).

Save A's context, restore B's — and note what got silently thrown away.
  • Thread switch within a process keeps the address space — cheaper (no TLB flush; tagged TLBs/ASIDs reduce even cross-process cost on modern CPUs).
  • Mode switch ≠ context switch: a system call enters the kernel and returns to the same thread — much cheaper. Interviewers love this distinction.
  • Voluntary vs involuntary: blocking on I/O (voluntary) vs preemption (involuntary). High involuntary switch rates in pidstat -w mean too many runnable threads competing — the classic oversubscribed-thread-pool signature.
  • This cost is precisely what virtual threads and event loops avoid: switching between virtual threads or event-loop tasks happens in user space in nanoseconds, no kernel entry, no TLB damage.

🔄 Likely follow-up questions

  • How do tagged TLBs (ASIDs/PCIDs) reduce the cross-process penalty?
  • How would you measure context-switch overhead in a running service?
  • Why are green/virtual threads cheaper to switch than kernel threads?