liveBook · Manning

Context switching

As explained in Grokking Concurrency

Context switching is the operating-system procedure of saving one task's execution state and restoring another task's state so execution can be transferred between them.

Imagine pausing a conversation to answer your phone, then returning to the same sentence afterward. Context switching works similarly: the operating system saves one task's execution context and restores another task's context so execution can move between them without losing progress. section 6.9

A task's context includes its current instruction, CPU flags, registers, variables, open files, and connections. The scheduler moves a selected task from the Ready state to Running, saves the running task's state, and loads the next task's stored state. When the task returns, it resumes as though only time has passed. section 6.9

Context switching supports multitasking but has different consequences depending on the work:

  • The operating system can alternate tasks even on a single core, creating the appearance of simultaneous execution without hardware parallelism. section 6.12 section 6.14
  • Switching between threads is generally faster than switching between processes because processes carry larger contexts; threads also share an address space. section 6.12
  • Too many tasks can waste useful time in the switching loop, especially when CPU-bound work could otherwise keep computing. section 6.14 section 10.10
  • When a task waits for I/O, the operating system can block it and run a Ready task instead, keeping the processor productive. section 10.10

A blocked request

Suppose one task is waiting for a disk or network response. Rather than leaving the CPU idle, the operating system stores that task in the Blocked state and gives another Ready task time to run. After the response arrives, the waiting task returns to Ready and may run again when selected. section 10.10

How Grokking Concurrency covers it

How deep it goes
Defines saved execution state and scheduler transitions, then contrasts switching costs for CPU-bound and I/O-bound work.
Examples
Uses a phone-call interruption and task states such as Ready, Running, and Blocked to make switching behavior concrete.
What it assumes
Builds from everyday interruption and basic task states rather than assuming prior operating-system or concurrency knowledge.
What you can do after
Evaluate when task switching helps responsiveness and when its overhead can degrade application performance.
How it connects
Connects context switching to multitasking, schedulers, processes, threads, CPU-bound work, and I/O-bound work.

Also explained in

Compare how 9 books explain context switching →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Concurrency. The section links point to the parts of the book it draws on.