TL;DR
A processor runs one instruction stream at a time, but a computer runs many processes at once. A context switch is the step where the Operating System stops one process, saves everything needed to resume it, loads the saved state of another, and lets that one run. Done fast, the switches make many programs appear to run together, at the cost of a short pause each time.
Builds on: Process (Running Program), Operating System · Leads to: Thread
Where it's used
Desktop multitasking. A laptop may have a browser, a music player and a text editor open at once, while the processor has only a few cores. The operating system gives each program a short time slice (the length of time it runs before the system may switch), often a few milliseconds, and context switches between programs many times a second. You perceive the programs as running together.
Web servers. A server that handles thousands of connections often runs many threads, one per request or a pool of workers. A thread is one flow of instructions that shares its process's memory. Each thread blocks while it waits for a disk or a network reply. The operating system switches to another thread while it waits, so the processor is not idle. Engineers watch the switching rate because too many switches waste time.
Real-time control. A robot controller runs a sensor loop and a motor loop, each with a deadline. The operating system switches between them on a fixed schedule, so the sensor loop gets the processor before the motor loop needs its next command.
How it works
Take one processor and two processes. Process A is counting, and process B is computing a sum. Each process has saved state: a program counter (the address of the next instruction), registers (small values the processor is working on), and a stack pointer (where the process keeps its function-call data). Use tiny numbers.
flowchart LR A[Process A runs] --> T[Timer interrupt] T --> S[Save A's state] S --> L[Load B's state] L --> B[Process B runs]
-
Process A is running. Its program counter is 100 and its register R holds 5. The processor executes instruction 100, then 101, and so on. Check: the processor is working for A alone.
-
A timer fires, an event called an interrupt, which is a signal that makes the processor pause its current work and run a handler. The processor stops A's instruction stream and hands control to the operating system's code. Check: A has not finished; it is only paused.
-
The operating system saves A's state into A's record: program counter 101 and register R equal to 6. Check: if A resumes later, it will continue at instruction 101 with R equal to 6.
-
The operating system chooses B from the list of processes that are ready to run (often kept as a Queue). Its record says program counter 200 and register R equal to 40. Check: the record holds everything needed to resume B.
-
The operating system loads B's values into the processor: program counter 200, register R equal to 40. Then it returns control. Check: B continues exactly where it stopped.
-
Later, the cycle repeats with A's saved state restored. Check: A sees no change in its own values, only a gap in time.
The name of the idea comes from step 3 and step 5. The "context" of a process is the set of values that define where it is and what it holds. Switching the context is saving one set and loading another.
The math
Let be the time slice, the time a process runs before the operating system switches, and let be the time one switch costs. Each slice does useful work for and wastes on the switch. The fraction of processor time lost to switching is
Step 3 in symbols: the cost of saving state
If the processor has registers, each stored value costs a memory write, and each loaded value a memory read. Saving and loading the whole set takes time roughly proportional to . The direct cost is therefore set by the size of the state, which the next steps in the walkthrough do not change.
Step 5 in symbols: useful time per slice
Over a long run with a fixed slice , the processor spends of its time on useful work. When , the overhead is small, because .
The plot shows overhead against the slice length for a switch that costs 0.01 milliseconds.
- overhead = s / (q + s), s = 0.01 ms
Worked examples
Process A has program counter 100 and register R = 5. Process B has program counter 200 and register R = 40.
- A runs and reaches an interrupt at instruction 100, with R = 6 after the last instruction.
- The operating system saves A: program counter 101, R = 6.
- It loads B: program counter 200, R = 40.
- B runs. Its R starts at 40, not 6.
- Interpretation: B's values were kept intact while A was paused, so B does not see A's work.
A switch costs ms. Compare two slice lengths.
- With ms, compute ms.
- Compute the overhead , which is 0.1 percent.
- With ms, compute ms.
- Compute the overhead , which is about 9.1 percent.
- Interpretation: the shorter slice makes the system more responsive, but it loses about 90 times as much time to switching. The choice of slice length trades responsiveness against throughput.
A server has 200 threads ready to run and gives each a slice of ms. A direct switch costs 5 microseconds. A thread that resumes after a switch also must reload its working data into the cache (a small, fast memory near the processor), a cache refill that costs about 50 microseconds more. The total switch cost is microseconds, which is ms.
- Compute ms.
- Compute the overhead , which is 1.36 percent.
- Compute how many switches happen per second: each slice is 4 ms, so there are switches per second.
- Interpretation: the switches cost a little over 1 percent of the processor, mostly from the cache refill. The direct cost of saving registers is small by comparison, so the cache effect is what an engineer studies.
Try it: the same server moves to slices of ms, with the same ms. How many switches per second happen now, and what is the overhead? Answer: switches per second, and the overhead is , about 2.7 percent.
Common mistakes and tradeoffs
It is tempting to think a context switch is just a function call. In fact a function call stays inside one process and keeps the same memory. A context switch changes which process owns the processor, so the operating system must also change which memory the processor is allowed to read, as covered in Virtual Memory.
It is tempting to think the switch cost is only the registers. In fact the new process often finds its data missing from the fast cache, a small memory close to the processor. It must then reload its data, a cache refill, so it runs slowly for a while after the switch. In the realistic example this cache effect was larger than the direct cost.
It is tempting to think more threads always means more parallel work. In fact a single processor core runs only one of them at a time, and every extra thread adds switches. Threads share memory, so they also need coordination when they touch the same data. Threads help when they wait on slow input and output, not when they all need the processor.
When to use it: whenever more runnable programs exist than processors, or when a program waits for slow input and output and the processor should do something else.
When not to use it: in tight loops where one task must run without interruption, and where a dedicated processor is available. Some systems pin a task to a core for this reason.
Alternatives: cooperative multitasking, where a program gives up the processor voluntarily, avoids the timer interrupt but relies on programs to behave. Lightweight Thread designs and user-level schedulers switch without entering the kernel, at the cost of more programming effort.
History
Early computers ran one job at a time, and the processor sat idle whenever a job waited for a card reader or a tape. In the early 1960s, time-sharing systems such as CTSS at MIT let many users share one computer by switching between their jobs quickly enough that each user seemed to have a machine of their own. The switch itself was the central mechanism.
Hardware timers, which raise an interrupt after a set time, made the forced switch practical. Operating systems in the following decades refined the saved state and the choice of which process runs next. Modern systems switch processes and threads thousands of times a second, and the cost is now dominated by cache and memory effects.
Recap
- A process is a program that is running, with saved state: where it is, and what its values are.
- A context switch saves the running process's state and loads another's, so the processor can share its time.
- The overhead is the switch cost divided by the slice length plus the switch cost.
- Short slices improve responsiveness and raise overhead; long slices reduce overhead and slow responses.
- Read next: Thread for units of work that share a process's memory, and Virtual Memory for what changes when the processor switches to a different process.
Check yourself
QuestionRecall: what three kinds of saved state define where a process is and what it holds?Show answer
A program counter (the address of the next instruction), registers (the small working values), and a stack pointer (where function-call data is kept). Together they are the context the operating system saves and loads.
QuestionComputation: a switch costs 0.02 ms and the time slice is 2 ms. What fraction of processor time is lost to switching?Show answer
The overhead is , which is about 1 percent.
QuestionWhy: why is a context switch more expensive than a normal function call?Show answer
A function call stays inside the same process, with the same memory and cached data. A context switch changes which process owns the processor, so the memory the processor may read changes too, and the new process's data is often missing from the cache, which slows it down for a while.
QuestionApplied: a team sees its web server slow down when they raise the number of worker threads from 50 to 500. Using only what this lesson says, what is the likely cause, and what would you check?Show answer
More threads mean more switches, and each switch costs time that does no useful work, and each resumed thread may find its cache cold. The likely cause is switching overhead, so the team should measure the switch rate and the cache miss rate, and check whether the threads are waiting on input and output or competing for the processor.
Sources
- Context switch (Wikipedia): https://en.wikipedia.org/wiki/Context_switch
- Scheduling (computing) (Wikipedia): https://en.wikipedia.org/wiki/Scheduling_(computing)
- Time-sharing (Wikipedia): https://en.wikipedia.org/wiki/Time-sharing