Context Switching in OS
The kernel saves the CPU state of the running process, picks another process and loads its state. No user work runs meanwhile, and the cold cache afterwards costs more than the switch itself.
What a Context Switch Does
Context switching is how an operating system shares one CPU between many processes. The kernel stops the running process, saves everything the CPU holds for it, loads the saved state of another process and lets that one continue exactly where it stopped.
The context is the part of the CPU's state that belongs to one process: the program counter, the general registers, the stack pointer, the status flags, and the memory-management state such as the page table base register. The kernel saves it in the process's PCB; the PCB lesson covers each field.
If any register were left out, the process would resume with another process's value in it and compute the wrong thing. That is why the save is complete, not selective.
- Saved: PC, registers, stack pointer, flags, page table base
- Stored in the PCB, which stays in kernel memory while the process waits
- On one CPU, switching many times a second makes processes appear to run together
Steps in Context Switching
- An interrupt or system call enters the kernel; the hardware saves the user PC and flags.
- The kernel copies the remaining registers of the running process into its PCB.
- It sets that process's state to ready (or waiting) and puts the PCB in the matching queue.
- The short-term scheduler picks the next process from the ready queue.
- The page table base register is loaded with the new process's table; without ASID tags the TLB is flushed.
- The new process's registers are loaded from its PCB and its state set to running.
- Return to user mode; the restored PC makes the new process continue.
The steps in context switching run inside the kernel, after an interrupt or a system call has already moved the CPU into kernel mode. The order matters: the old state must be safe before anything overwrites it, and the program counter is loaded last because loading it is what hands the CPU to the new process.
- Steps 2 to 6 do no user work; they are pure overhead
- The kernel stack pointer changes too, since each process has its own kernel stack
- The dispatcher is the code that performs steps 5 to 7
What Triggers a Switch
A process does not choose when it is switched out, except when it gives up the CPU itself. A timer interrupt ends its time slice and lets the scheduler run; this is what makes preemptive scheduling possible. A blocking system call, such as a disk read or waiting on a lock, moves it to the waiting state, so keeping the CPU would waste it.
A higher-priority process becoming ready, often because an I/O interrupt completed its request, can preempt the running one under a priority scheduler. A process also gives up the CPU when it exits or calls yield.
- Involuntary: timer interrupt, preemption by a higher-priority process
- Voluntary: blocking I/O, waiting on a lock, yield, exit
- An interrupt alone is not a switch; the kernel may return to the same process
Terms, operations, and practical uses
Core vocabulary
- ContextThe CPU state of a process: PC, registers, flags, memory-management state.
- DispatcherKernel code that loads the chosen process and returns to user mode.
- Mode switchUser to kernel mode or back, without changing process.
- ASIDAddress-space tag on TLB entries so a switch need not flush the TLB.
Formulas and rules
- Overheadswitch cost ÷ (time slice + switch cost)
- 50 µs slice, 30 µs switch30 ÷ 80 = 37.5% lost
- 4 ms slice, 30 µs switch30 ÷ 4030 = 0.74% lost
- Ordersave old state first; load the PC last
Related lessons
- Process States and PCBWhat each PCB field holds.
- Interrupts in OSThe timer interrupt that starts a preemptive switch.
- Round Robin SchedulingWhere the time slice and switch cost meet.
- Translation Lookaside BufferWhy a switch can leave the TLB cold.
One context switch, register by register
SWITCH_US = 5 # save + schedule + restore
REFILL_US = 25 # cold cache and TLB afterwards
COST_US = SWITCH_US + REFILL_US
def overhead(slice_us):
"""Share of CPU time lost: cost / (slice + cost)."""
return COST_US / (slice_us + COST_US)
def simulate(slice_us, total_us):
"""Round robin for total_us: every slice is preceded by one switch."""
elapsed = switches = useful = 0
while elapsed + COST_US < total_us:
elapsed += COST_US
switches += 1
ran = min(slice_us, total_us - elapsed)
useful += ran
elapsed += ran
return switches, useful
def main():
for slice_us in (50, 500, 4000):
switches, useful = simulate(slice_us, 20000)
print(f"slice {slice_us:>4} us switches {switches:>3} "
f"useful {useful:>5} of 20000 us overhead {overhead(slice_us) * 100:.2f}%")
if __name__ == "__main__":
main()#include <algorithm>
#include <cstdio>
const int SWITCH_US = 5; // save + schedule + restore
const int REFILL_US = 25; // cold cache and TLB afterwards
const int COST_US = SWITCH_US + REFILL_US;
// Share of CPU time lost: cost / (slice + cost).
double overhead(int sliceUs) { return (double)COST_US / (sliceUs + COST_US); }
// Round robin for totalUs: every slice is preceded by one switch.
void simulate(int sliceUs, int totalUs, int& switches, int& useful) {
int elapsed = 0;
switches = useful = 0;
while (elapsed + COST_US < totalUs) {
elapsed += COST_US;
switches++;
int ran = std::min(sliceUs, totalUs - elapsed);
useful += ran;
elapsed += ran;
}
}
int main() {
for (int sliceUs : {50, 500, 4000}) {
int switches, useful;
simulate(sliceUs, 20000, switches, useful);
std::printf("slice %4d us switches %3d useful %5d of 20000 us overhead %.2f%%\n",
sliceUs, switches, useful, overhead(sliceUs) * 100);
}
}public class Main {
static final int SWITCH_US = 5; // save + schedule + restore
static final int REFILL_US = 25; // cold cache and TLB afterwards
static final int COST_US = SWITCH_US + REFILL_US;
// Share of CPU time lost: cost / (slice + cost).
static double overhead(int sliceUs) {
return (double) COST_US / (sliceUs + COST_US);
}
// Round robin for totalUs: every slice is preceded by one switch.
static int[] simulate(int sliceUs, int totalUs) {
int elapsed = 0, switches = 0, useful = 0;
while (elapsed + COST_US < totalUs) {
elapsed += COST_US;
switches++;
int ran = Math.min(sliceUs, totalUs - elapsed);
useful += ran;
elapsed += ran;
}
return new int[] {switches, useful};
}
public static void main(String[] args) {
for (int sliceUs : new int[] {50, 500, 4000}) {
int[] r = simulate(sliceUs, 20000);
System.out.printf("slice %4d us switches %3d useful %5d of 20000 us overhead %.2f%%%n",
sliceUs, r[0], r[1], overhead(sliceUs) * 100);
}
}
}Step through it
Running on P1 running, timer interrupt, scheduler picks P2; switch cost 5 µs direct + 25 µs cache and TLB refill
Context Switch vs Mode Switch
The difference between a context switch and a mode switch is a common exam question because the two are easy to confuse. A mode switch moves the CPU between user mode and kernel mode, as every system call does, but the same process keeps running. A context switch changes which process runs. Every context switch needs a mode switch to get into the kernel; most mode switches end without a context switch.
Threads of the same process sit in between: switching them saves and loads registers, but the address space stays the same, so the page table base and the TLB are left alone.
| Mode switch | Thread switch (same process) | Process switch | |
|---|---|---|---|
| Changes | Privilege level only | Running thread | Running process |
| State saved | User PC, flags, a few registers | All registers | All registers and memory state |
| Address space | Unchanged | Unchanged | New page table |
| TLB and caches | Kept | Kept | TLB flushed without ASIDs; caches go cold |
| Typical cost | Tens to hundreds of ns | A few µs | A few µs, plus refill time |
- System call: mode switch, same process
- Timer interrupt that picks another process: mode switch plus context switch
Context Switch Overhead
Context switch overhead has two parts. The direct cost is the register save and restore plus the scheduler run, a few microseconds on current hardware; this lesson uses 5 µs. The indirect cost comes afterwards: the new process finds the caches full of the old one's data and, without ASIDs, an empty TLB, so it runs slowly until its working set is loaded again. This lesson uses 25 µs for that, giving an effective cost of 30 µs per switch.
The share of CPU time lost is switch cost ÷ (time slice + switch cost). With a 50 µs slice that is 30 ÷ 80 = 37.5%, more than a third of the machine. With a 4 ms slice it is 30 ÷ 4030 = 0.74%, while still switching about 250 times a second. That is why time slices are a few milliseconds long.
- Register file size: wide vector registers add to every save
- ASID or PCID support keeps TLB entries across switches
- Cache footprint of the processes involved
- Length of the kernel path, including the scheduler
- Threads of one process switch more cheaply than processes