Sub topic 6
Context Switching and Its Cost
This chapter assumes you know the process states and the PCB (Process Control Block) from the previous chapters. It also assumes you know the difference between user mode and kernel mode, and that you can read short C programs. The chapter covers what a context switch does step by step, what makes it expensive, and how to account for it in GATE calculations.
What a context switch is
A context switch is the act of stopping one running process (or thread) and giving the CPU to another. The context is everything the CPU needs to resume a process exactly where it stopped. It consists of the program counter, the general-purpose registers, the stack pointer, the status flags, and the memory-management state (such as the page-table base register).
The kernel keeps a saved copy of this context in the process's PCB. The switch copies the outgoing process's context into its PCB and loads the incoming process's context from its PCB.
A context switch is not the same as a mode switch:
| Event | User to kernel mode | Process changes | Typical example |
|---|---|---|---|
| Mode switch | Yes | No | A system call such as `getpid` that returns to the same process |
| Context switch | Usually, since it happens in kernel code | Yes | Timer interrupt picks another process |
| Interrupt handling | Yes | Only if the scheduler decides so | Keyboard interrupt handled, original process resumes |
A mode switch saves only a little state. A full context switch saves and restores a whole process context and also runs the scheduler.
What triggers a switch
The kernel runs the scheduler, and may switch, in these cases:
- A timer interrupt ends the running process's time slice (preemption).
- The running process makes a blocking system call, such as
readon an empty pipe, and moves to the waiting state. - An I/O completion interrupt makes a higher-priority process ready.
- The process calls a yield operation, or it terminates.
Cases 2 and 4 are voluntary switches because the process gives up the CPU. Cases 1 and 3 are involuntary (preempted). On Linux, /proc/<pid>/status reports both counts as voluntary_ctxt_switches and nonvoluntary_ctxt_switches.
The steps of a switch
Suppose process P1 is running and the kernel switches to P2.
The dispatcher is the kernel module that does the final part of this work: switching context, switching to user mode, and jumping to the saved program counter. The time between stopping P1 and starting P2 is the dispatch latency. During it, no user instruction executes, so it is pure overhead.
Why a switch costs time
Two kinds of cost matter.
Direct cost
This is the work the kernel does. It saves and restores registers, updates PCBs and queues, and runs the scheduling decision. It also changes the address space by loading a new page-table base. On modern hardware this takes roughly one to a few microseconds. It depends on the number of registers, including floating-point and vector state, and on the hardware support.
Some architectures provide several register sets, so a switch only changes a pointer to the active set. If there are more active processes than register sets, the system falls back to copying.
Indirect cost
This cost appears after the switch and is often larger:
- TLB (translation lookaside buffer). Cached address translations belong to the old address space. If the TLB has no address-space tags, it must be flushed, and P2 starts with many TLB misses. Tagged TLBs (with ASIDs, address-space identifiers) avoid the flush.
- CPU caches. P2's data is probably not in the cache, because P1's data fills it. P2 suffers cache misses until its working set is loaded again.
- Branch predictors and pipeline. The pipeline drains, and predictor state learned for P1 is of little use to P2.
Switching between two threads of the same process avoids the address-space change, so it is cheaper. Switching between user-level threads in a user-space library needs no kernel entry at all, so it is cheaper still. The thread chapters cover this in more detail.
Measuring a switch
The program below estimates the cost on Linux. Two processes are pinned to the same CPU and pass one byte back and forth through two pipes. Each blocking read forces the kernel to switch to the other process, so one round trip contains two context switches.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sched.h>
#include <time.h>
#include <sys/wait.h>
#define ROUNDS 100000
int main(void) {
int p2c[2], c2p[2];
if (pipe(p2c) < 0 || pipe(c2p) < 0) {
perror("pipe");
return 1;
}
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(0, &set);
if (sched_setaffinity(0, sizeof set, &set) < 0) {
perror("sched_setaffinity");
return 1;
}
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return 1;
}
if (pid == 0) {
char b;
for (int i = 0; i < ROUNDS; i++) {
if (read(p2c[0], &b, 1) != 1) _exit(1);
if (write(c2p[1], &b, 1) != 1) _exit(1);
}
_exit(0);
}
char b = 'x';
struct timespec t0, t1;
clock_gettime(CLOCK_MONOTONIC, &t0);
for (int i = 0; i < ROUNDS; i++) {
if (write(p2c[1], &b, 1) != 1) return 1;
if (read(c2p[0], &b, 1) != 1) return 1;
}
clock_gettime(CLOCK_MONOTONIC, &t1);
waitpid(pid, NULL, 0);
double ns = (t1.tv_sec - t0.tv_sec) * 1e9 + (t1.tv_nsec - t0.tv_nsec);
printf("about %.0f ns per switch\n", ns / (2.0 * ROUNDS));
return 0;
}The child inherits the CPU affinity from the parent through fork, so both processes share CPU 0. The printed number includes the system call costs of read and write, so it overestimates the pure switch time. Treat it as an upper bound that shows the order of magnitude.
Switch cost in scheduling calculations
GATE questions sometimes add a switch overhead to a scheduling problem. The usual model is that each switch takes a fixed time s, during which no process runs.
For Round Robin with quantum q, where each process uses its whole quantum, the fraction of CPU time spent on useful work is:
CPU efficiency = q / (q + s)
Two consequences follow:
- A very small q makes the switch overhead dominate, because s becomes large compared with q.
- A very large q removes the overhead, but Round Robin then behaves like FCFS and response time suffers.
When a process finishes before using its full quantum, the switch still happens, but the useful part of that slice is shorter. Read the question to see whether the overhead is charged at the start of the first process and after the last one. Unless the question says otherwise, count one switch between each pair of consecutive different processes.
Another point that is often tested is that a switch does not occur when the scheduler picks the same process again. If only one process is ready, the dispatcher resumes it without a full switch.
Common errors
- Saying every system call causes a context switch. Most system calls only cause a mode switch and return to the same process.
- Saying every interrupt causes a context switch. The handler normally returns to the interrupted process.
- Forgetting that the PCB is the storage place for the saved context, and that the kernel stack holds the state during the switch.
- Counting the cost only as register copying. The cache and TLB effects often cost more.
Exercise
A system uses Round Robin with a time quantum of 10 ms. Each context switch takes 2 ms. Every process always uses its full quantum. What fraction of CPU time goes to useful work, and what is it if the quantum is changed to 2 ms?
Show answer
Efficiency is q / (q + s). For q = 10 ms and s = 2 ms it is 10 / 12, about 83.3%. For q = 2 ms it is 2 / 4 = 50%. Halving the quantum several times shows why very small quanta waste half or more of the CPU.
Exercise
A process calls getpid() and the call returns immediately. Did a context switch occur? What if it calls read() on an empty pipe and blocks?
Show answer
For getpid() there was a mode switch to kernel mode and back, but no context switch, because the same process resumes. When read() blocks, the kernel moves the process to the waiting state and the scheduler runs another process, so a context switch occurs. This is a voluntary switch.