Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 66 Β· Processes

Context Switching

Understand how the OS saves one process's state and loads another's: the steps of a context switch, what triggers it, its overhead, and a simulator that measures the cost.

A CPU core can only run one instruction stream at a time, yet your computer seems to run dozens of programs at once. The trick is to switch between them so quickly that it looks simultaneous. The act of stopping one process, saving where it was, and starting (or resuming) another is a context switch.

Context switching is what makes multitasking possible, but it is also pure overhead: while the OS is switching, no user program makes progress. In this lesson you will learn what exactly is saved and restored, what triggers a switch, why it costs time, and how to reason about the trade-off between switching often (responsive) and rarely (efficient).

A context switch in four steps

Save Registers and PC go into the old PCB.
Update state Old process moves to ready or waiting.
Choose Scheduler picks the next process.
Restore Load registers and PC from the new PCB.

The CPU does no useful user work during these steps.

1 / 2

What is the "context"?

The context of a process is everything needed to continue it later exactly as if it had never stopped:

  • the program counter and stack pointer,
  • all general-purpose and status registers,
  • the memory-management state (which page table is active),
  • some kernel bookkeeping such as open file tables and accounting data (kept in the PCB).

When a process is stopped, the kernel copies its context into the PCB. When it is chosen again, the kernel copies the context from the PCB back into the CPU.

What triggers a context switch?

  1. Time slice expiry. The timer interrupt fires and the OS preempts the running process.
  2. Blocking. The process asks for I/O or waits for a lock, so it cannot use the CPU.
  3. A higher-priority process becomes ready, for example after an I/O completion or a signal.
  4. Voluntary yield. The process calls something like sched_yield or sleep.
  5. Termination. The process exits and the CPU needs a new job.

An interrupt alone is not a context switch. The CPU saves a little state, runs the interrupt handler and returns to the same process (a mode switch). Only if the handler decides another process should run does the full context switch happen. Mode switches are cheaper than context switches.

The steps in detail

sequenceDiagram
    participant P0 as Process P0
    participant K as Kernel
    participant P1 as Process P1
    P0->>K: interrupt or system call
    K->>K: save P0 context into PCB0
    K->>K: scheduler picks P1
    K->>K: load P1 context from PCB1
    K->>P1: return to user mode
    Note over P0,P1: P0 waits in the ready or waiting queue

Between "interrupt" and "return", only the kernel runs.

The piece of the kernel that performs the final hand-over is the dispatcher (dispatcher vs. scheduler). The time it takes to stop one process and start another is the dispatch latency.

Why a context switch is expensive

The register copying itself takes microseconds. The hidden costs are larger:

  • Cache and TLB pollution. The new process's data is not in the CPU caches, so it runs slowly at first (cache misses). The TLB, which caches address translations, is often flushed on an address-space change.
  • Pipeline flush. The CPU's instruction pipeline is emptied.
  • Scheduler work. Choosing the next process takes time.
  • Memory-map switch. Loading a new page table root.

Threads of the same process switch faster than separate processes because they share one address space, so no page-table change or TLB flush is needed (threads).

Measuring the overhead

If a context switch takes s ms and the time slice is q ms, the fraction of time wasted is roughly s / (q + s). A tiny slice makes the system feel responsive but wastes a lot on switching. The simulator below runs three jobs under a time slice and counts switches and overhead for different slice sizes.

Python Time slice vs. overhead

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The efficiency climbs as the quantum grows, but a huge quantum approaches first-come first-served behavior and interactive jobs have to wait longer. Choosing the quantum is a design decision you will revisit in round robin.

Seeing a context switch in code

Here is a context switch in miniature: two "programs" are generators that can be paused at yield and resumed with their local variables intact. The generator object plays the role of the PCB: it remembers exactly where each program stopped.

Python Pausing and resuming programs

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Practical consequences

  • Too many runnable processes or threads means more switching and more cache misses; this is why servers use thread pools.
  • High involuntary context switches in monitoring tools (vmstat, pidstat) point to CPU contention; high voluntary ones point to processes waiting on I/O or locks.
  • Hardware can help: some CPUs offer multiple register sets or hyper-threading to speed up switches.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. What is saved in the PCB during a context switch?

    The kernel stores the CPU context so the process can resume exactly where it stopped.
  2. 2. Why is context switching called pure overhead?

    The CPU time spent saving, choosing and restoring contexts could otherwise have run user code.
  3. 3. If the time slice is made very small, what usually happens?

    A larger share of time goes to switching, so efficiency falls even though response time improves.
  4. 4. Which switch is typically faster?

    Threads of one process share an address space, so no page-table change or TLB flush is needed.

Summary

  • A context switch saves one process's CPU state into its PCB and loads another's.
  • It is triggered by timer interrupts, blocking, higher-priority arrivals, yielding or exit.
  • It is overhead: register copying plus cache, TLB and pipeline effects.
  • Efficiency is about q / (q + s); very small time slices waste time.
  • Thread switches within a process are cheaper than process switches.

Next: Process Creation and Termination