Context switch

On this page 8

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.

  1. The CPU enters kernel mode and the current thread’s user-mode registers are saved on its kernel stack.
  2. The scheduler selects the next runnable thread according to priority and policy.
  3. The switch routine saves the remaining callee-saved registers and stack pointer in the outgoing thread’s control block.
  4. If the next thread belongs to another process, the kernel loads its page table base into the memory management unit.
  5. 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.

ComponentRoleSaved on every switch
General-purpose registersHold working values of the programYes
Program counter and stack pointerMark where execution resumesYes
Status or flags registerHolds condition codes and mode bitsYes
Floating-point and vector registersHold SIMD and FPU stateOften lazily or on demand
Page table base registerSelects the address spaceOnly between processes
Kernel stack pointerPoints to per-thread kernel stackYes
Components of the execution context

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.

TypeTriggerTypical cause
Voluntary switchThread blocks or yieldsWaiting for I/O, a lock or a sleep timer
Involuntary switchScheduler preempts the threadTime slice expired or higher-priority thread ready
Thread switch within a processSame address spaceWorker threads of one application
Process switchDifferent address spaceTwo separate programs sharing a core
Interrupt-driven switchDevice or timer interruptNetwork packet or disk completion wakes a thread
Main kinds of context switches

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.

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.

OperationWhat changesRelative cost
Mode switchPrivilege level only, same threadLowest
Thread context switchRegisters and stack, same address spaceModerate
Process context switchRegisters, stack and address spaceHigher
User-level thread switchRegisters managed by a runtime libraryVery low, no kernel entry
Virtual machine switchEntire guest CPU stateHighest
Context switch and neighboring operations

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.

SymptomLikely causeTypical remedy
Many involuntary switchesMore runnable threads than coresSize thread pools to core count
Many voluntary switchesFine-grained locking or blocking I/OUse asynchronous I/O or coarser locks
Latency spikes in real-time workPreemption by other tasksRaise priority or isolate CPU cores
Poor cache hit rateThreads migrating between coresSet CPU affinity for hot threads
High kernel CPU timeFrequent short sleeps and wakeupsBatch work and reduce timer wakeups
Diagnosing excessive context switching

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.