Search

Search papers and lessons

Context Switch

Level 2 · 10 min read

A context switch saves the state of the program that is running and restores the saved state of another, so one processor can share its time among many programs.

On this page

  • Colour = topic mix
  • Systems
  • ReadReady to readNot yet

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]
  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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 qq be the time slice, the time a process runs before the operating system switches, and let ss be the time one switch costs. Each slice does useful work for qq and wastes ss on the switch. The fraction of processor time lost to switching is overhead=sq+s.\text{overhead} = \frac{s}{q + s}.

Step 3 in symbols: the cost of saving state

If the processor has rr 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 rr. The direct cost ss 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 qq, the processor spends qq+s\frac{q}{q + s} of its time on useful work. When q≫sq \gg s, the overhead is small, because sq+s≈sq\frac{s}{q+s} \approx \frac{s}{q}.

The plot shows overhead against the slice length for a switch that costs 0.01 milliseconds.

24681000.020.040.060.080.1time slice q (ms)fraction lost
  • overhead = s / (q + s), s = 0.01 ms
Long slices lose almost nothing to switching. Very short slices lose a large share of the processor.

Worked examples

Example
1. Tiny case: one register, one switch

Process A has program counter 100 and register R = 5. Process B has program counter 200 and register R = 40.

  1. A runs and reaches an interrupt at instruction 100, with R = 6 after the last instruction.
  2. The operating system saves A: program counter 101, R = 6.
  3. It loads B: program counter 200, R = 40.
  4. B runs. Its R starts at 40, not 6.
  5. Interpretation: B's values were kept intact while A was paused, so B does not see A's work.
Example
2. Standard case: overhead for two slice lengths

A switch costs s=0.01s = 0.01 ms. Compare two slice lengths.

  1. With q=10q = 10 ms, compute q+s=10.01q + s = 10.01 ms.
  2. Compute the overhead 0.0110.01≈0.001\frac{0.01}{10.01} \approx 0.001, which is 0.1 percent.
  3. With q=0.1q = 0.1 ms, compute q+s=0.11q + s = 0.11 ms.
  4. Compute the overhead 0.010.11≈0.091\frac{0.01}{0.11} \approx 0.091, which is about 9.1 percent.
  5. 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.
Example
3. Realistic case: a busy server

A server has 200 threads ready to run and gives each a slice of q=4q = 4 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 s=55s = 55 microseconds, which is 0.0550.055 ms.

  1. Compute q+s=4.000+0.055=4.055q + s = 4.000 + 0.055 = 4.055 ms.
  2. Compute the overhead 0.0554.055≈0.0136\frac{0.055}{4.055} \approx 0.0136, which is 1.36 percent.
  3. Compute how many switches happen per second: each slice is 4 ms, so there are 1000/4=2501000 / 4 = 250 switches per second.
  4. 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 q=2q = 2 ms, with the same s=0.055s = 0.055 ms. How many switches per second happen now, and what is the overhead? Answer: 1000/2=5001000 / 2 = 500 switches per second, and the overhead is 0.0552.055≈0.0268\frac{0.055}{2.055} \approx 0.0268, 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 sq+s=0.022.02≈0.0099\frac{s}{q + s} = \frac{0.02}{2.02} \approx 0.0099, 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