AlgoMaster Logo

Context Switching

High Priority16 min readUpdated August 14, 2026

A logical CPU executes one instruction stream at a time, yet a laptop may keep a browser responsive while compiling code, playing music, and running a database.

The operating system creates this illusion of simultaneous progress by repeatedly changing which thread owns each CPU. The mechanism that makes each suspended computation continue from exactly where it stopped is a context switch.

A context switch saves the execution state of one thread and restores the saved state of another so the CPU can resume the second thread.

Context switching is essential for multitasking. It is also not free. The kernel performs bookkeeping during the switch, and the incoming thread may find that useful CPU cache and translation state have grown cold.

This chapter follows a context switch step by step, distinguishes context switches from mode switches, examines their direct and locality-related costs, and shows how to measure them on Linux.

Premium Content

Subscribe to unlock full access to this content and more premium articles.