A context switch is the operation in which an operating system kernel saves the execution state of the thread or process currently running on a CPU core and restores the saved state of another, so that the core continues with different work. Among OS fundamentals, it is the mechanism that makes multitasking possible on hardware that executes only one instruction stream per core at a time.
In operating systems such as Windows, macOS and Linux, context switches happen thousands of times per second on each core. They are invisible to applications, but their frequency and cost shape system responsiveness, throughput and latency.
How the kernel performs a context switch
A context switch begins when control enters the kernel, either through a timer interrupt, a hardware interrupt, a system call or a fault. The process scheduler then decides which runnable thread should use the core next, and the kernel’s low-level switch routine swaps the execution context.
- The CPU enters kernel mode and the current thread’s user-mode registers are saved on its kernel stack.
- The scheduler selects the next runnable thread according to priority and policy.
- The switch routine saves the remaining callee-saved registers and stack pointer in the outgoing thread’s control block.
- If the next thread belongs to another process, the kernel loads its page table base into the memory management unit.
- The kernel restores the incoming thread’s registers and returns to its saved program counter.
The state that must be saved and restored is called the execution context. Its exact contents depend on the processor architecture and on whether the switch crosses a process boundary.
| Component | Role | Saved on every switch |
|---|---|---|
| General-purpose registers | Hold working values of the program | Yes |
| Program counter and stack pointer | Mark where execution resumes | Yes |
| Status or flags register | Holds condition codes and mode bits | Yes |
| Floating-point and vector registers | Hold SIMD and FPU state | Often lazily or on demand |
| Page table base register | Selects the address space | Only between processes |
| Kernel stack pointer | Points to per-thread kernel stack | Yes |
Types of context switches
Context switches are classified by what triggers them and by what state changes. The distinction between voluntary and involuntary switches is particularly useful when diagnosing performance problems.
| Type | Trigger | Typical cause |
|---|---|---|
| Voluntary switch | Thread blocks or yields | Waiting for I/O, a lock or a sleep timer |
| Involuntary switch | Scheduler preempts the thread | Time slice expired or higher-priority thread ready |
| Thread switch within a process | Same address space | Worker threads of one application |
| Process switch | Different address space | Two separate programs sharing a core |
| Interrupt-driven switch | Device or timer interrupt | Network packet or disk completion wakes a thread |
A high rate of voluntary switches usually indicates I/O-bound or lock-heavy code, while a high rate of involuntary switches suggests CPU contention, with more runnable threads than available cores.
Context switch compared with related operations
A context switch is often confused with a mode switch, which occurs on every system call. A mode switch moves a thread from user space to kernel space and back without changing which thread runs, so it is considerably cheaper.
| Operation | What changes | Relative cost |
|---|---|---|
| Mode switch | Privilege level only, same thread | Lowest |
| Thread context switch | Registers and stack, same address space | Moderate |
| Process context switch | Registers, stack and address space | Higher |
| User-level thread switch | Registers managed by a runtime library | Very low, no kernel entry |
| Virtual machine switch | Entire guest CPU state | Highest |
Runtimes for green threads, coroutines and goroutines perform switches in user space, avoiding kernel entry entirely. This is why languages with lightweight concurrency can run hundreds of thousands of tasks on a handful of operating system threads.
The real cost of switching
The direct cost of a context switch on a modern x86-64 or ARM processor is typically between about one and several microseconds, depending on the CPU, the kernel and security mitigations. The indirect cost is often larger and harder to measure.
- Cache pollution: the incoming thread finds its data evicted from L1 and L2 caches and must reload it from slower memory.
- TLB flushes: changing the address space can invalidate translation lookaside buffer entries, although PCID on x86 and ASID on ARM tag entries to reduce this.
- Branch predictor disruption: learned prediction history may no longer match the new code.
- Security mitigations: protections against Meltdown and Spectre, such as kernel page table isolation, add work to each kernel entry and exit.
Because of these effects, a workload that switches tens of thousands of times per second per core can lose a noticeable share of CPU time to overhead, even when each individual switch looks cheap.
Measuring and reducing context switches
Administrators measure context switches with standard operating system tools and reduce them through thread design, affinity and scheduling settings. The goal is not zero switches, which would prevent multitasking, but avoiding unnecessary switching.
| Symptom | Likely cause | Typical remedy |
|---|---|---|
| Many involuntary switches | More runnable threads than cores | Size thread pools to core count |
| Many voluntary switches | Fine-grained locking or blocking I/O | Use asynchronous I/O or coarser locks |
| Latency spikes in real-time work | Preemption by other tasks | Raise priority or isolate CPU cores |
| Poor cache hit rate | Threads migrating between cores | Set CPU affinity for hot threads |
| High kernel CPU time | Frequent short sleeps and wakeups | Batch work and reduce timer wakeups |
On Linux, the vmstat column cs shows system-wide switches per second, and pidstat -w separates voluntary from involuntary switches per process. Windows exposes the Context Switches/sec counter in Performance Monitor, and macOS reports per-thread switch counts in Instruments.
Common misconceptions
- A system call is not a context switch unless it blocks and the scheduler runs another thread.
- More threads do not mean more speed: beyond the number of cores, extra CPU-bound threads mostly add switching overhead.
- Interrupt handling is not always a full switch: the interrupted thread’s context is partly preserved, but the scheduler may not run at all.
- Switch counts alone are not a problem: a high rate matters only when it coincides with lost throughput or latency.
The idea in brief
A computer appears to run many programs at once, but each processor core really works on one task at a time. A context switch is the moment when the computer puts one task aside and picks up another.
Think of a chef cooking several dishes on one stove burner. Before moving a pan, the chef notes exactly where each recipe stopped, so it can continue later without mistakes. That note is the saved context. Switching quickly creates the impression that everything cooks at once, but every switch takes a little time, so too much switching slows the whole kitchen down.
A practical scenario
A web service on an eight-core Linux server uses a thread pool of 400 threads, one per connection. Under load, response times become erratic, and vmstat shows about 200,000 context switches per second, while pidstat -w reveals that most are involuntary.
The engineering team replaces the thread-per-connection design with an event-driven model that uses a small pool of 16 worker threads and asynchronous I/O. After the change, switching falls to roughly 20,000 per second, kernel CPU time drops, and the 99th percentile latency becomes stable. The outcome shows that matching runnable threads to available cores often improves performance more than adding hardware.