What is a context switch?
Why Interviewers Ask This
This is a classic screening question for Operating Systems roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.
Answer
A context switch is the process of saving the state (context) of the currently running process/thread and restoring the state of another process/thread so it can resume execution. It's how the OS implements multitasking — switching the CPU among multiple processes rapidly. Steps in a context switch: (1) Save CPU registers (PC, stack pointer, general-purpose registers, flags) into current process's PCB; (2) Update current process's state (Running → Ready or Waiting); (3) Select next process to run (scheduler); (4) Update memory management structures (switch page tables, flush TLB for different address space); (5) Load CPU registers from next process's PCB; (6) Resume execution of next process from saved program counter. Context switch overhead: purely overhead — the CPU is doing no useful work while switching. Takes hundreds of nanoseconds to microseconds. Modern CPUs have features to speed this up (PCID — Process Context Identifier — lets TLB retain entries across context switches). What triggers a context switch: timer interrupt (time quantum expired — Round Robin), I/O request (process blocks), system call, interrupt, higher priority process becomes ready. Thread context switch vs process context switch: thread switches within the same process are cheaper — no need to switch page tables or flush TLB (same address space). Only registers and stack need switching. Measuring: perf stat -e context-switches ./program. High context switches can indicate thrashing or too many threads competing for CPU.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Operating Systems answers easy to follow.