Context Switching
Saving one thread's registers and loading another's so the CPU can change jobs.
Level: intermediate
What is it?
A context switch changes which thread or process executes on a CPU. The OS saves the outgoing execution context, selects another runnable context, and restores its saved state. A switch may happen after a timer interrupt, blocking syscall, exception, or wake-up that changes scheduling decisions.
Why does it matter?
Context switching enables multitasking but is not free. Register save/restore, scheduler work, cache disruption, and address-space changes can add latency. Frequent switching may reduce useful throughput.
Mental model
Think of a CPU as a worker with a notebook. To change jobs, the OS records the current job's place and working state, then loads the next job's notes. The CPU continues from that job's saved instruction rather than starting over.
How it works
- A switch between threads in one process may keep the same address space; switching processes can require address-space changes.
- Kernel entry does not automatically mean another thread is selected; many syscalls return to the same caller.
- Switching cost includes direct save/restore and indirect effects such as cold caches and translation lookaside buffer pressure.
- Blocking I/O may cause the caller to yield until an event wakes it.
- Latency-sensitive systems must balance fairness, throughput, and switch frequency.
Steps
- Thread A runs until its time slice expires.
- The timer interrupt transfers control to the kernel, which records A's state.
- The scheduler selects ready thread B and restores B's saved registers and stack pointer.
- B resumes at its previous instruction; A remains ready unless it was blocked or terminated.
Real-world usage
- Explaining why thread count affects latency and throughput.
- Interpreting scheduler profiles and voluntary versus involuntary context switches.
- Choosing worker-pool sizes to reduce excess scheduling overhead.
Common mistakes
- Claiming every syscall causes a context switch to another task.
- Ignoring cache effects and considering only register save/restore.
- Using high thread counts as a substitute for measuring concurrency and contention.
Interview questions
Does every mode switch cause a context switch?
No. A user-to-kernel mode transition can return to the same thread. A context switch changes the scheduled execution context.
Why can a process switch cost more than switching threads in the same process?
It may change address-space mappings and cause more TLB/cache disruption, in addition to the scheduling and register work.