What is a context switch and why is it expensive?
A context switch is the mechanism by which the operating system's scheduler pauses one executing process or thread and resumes another. It is fundamental to multitasking—the OS creates the illusion of simultaneous execution by rapidly switching between tasks.
**What happens during a context switch**: The CPU state of the outgoing task must be fully saved to its Process Control Block (PCB) or Thread Control Block (TCB): all general-purpose registers, the program counter (where execution was), the stack pointer, CPU flags, and floating-point/SIMD register state. The scheduler then selects the next task, loads its saved state into the CPU registers, and resumes execution from where that task left off.
**Why context switches are expensive**: The register save/restore itself takes ~hundreds of nanoseconds and is relatively cheap. The real costs are indirect:
1. **TLB flush**: Each process has its own virtual-to-physical address mapping. Switching processes invalidates the TLB (Translation Lookaside Buffer), causing subsequent memory accesses to take slower page-table walks until the TLB warms up again. Thread context switches within the same process don't require a TLB flush (shared address space).
2. **CPU cache cold**: The outgoing task's working set was in L1/L2 cache. The new task's data is likely not. The first many memory accesses after a switch are cache misses, taking 100× longer than cache hits. This is the dominant cost for cache-sensitive workloads.
3. **Pipeline flush**: Modern CPUs use deep out-of-order execution pipelines. A context switch requires flushing the pipeline, discarding speculative work.
4. **Scheduler overhead**: The OS scheduler itself runs, selecting the next task from run queues—additional CPU cycles not doing user work.
Thread context switches are cheaper than process switches (no TLB flush, shared memory mappings), and user-space context switches (green threads, coroutines) are cheaper still—they only save/restore a minimal software stack frame, with no kernel involvement.
This cost is why high-performance servers prefer event-driven async models (asyncio, Node.js) over thread-per-request models: thousands of coroutines can multiplex on one thread with no context-switch overhead.
Explains what CPU state is saved/restored, identifies TLB flush and cache invalidation as the dominant costs, distinguishes thread vs. process switch cost.
Covers PCB/TCB mechanism, explains TLB flush and why it doesn't happen for thread switches within a process, quantifies relative costs (cache miss vs. cache hit), explains pipeline flush, and connects to practical design implications (async I/O vs. thread-per-request).
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment