G27
Self-checkedTier 1 11 min reados.context-switch

Context switching

Moving the CPU from one process to another: what the context is, the steps of a context switch (save, choose, restore), what triggers one, the dispatcher and its latency, why it is pure overhead and what makes it expensive, and the efficiency of round robin with a switch cost.

Why it exists

One CPU can run only one process at a time, yet the operating system keeps several programs in progress. It does so by giving the CPU to a process for a while, then taking it away and giving it to another, and later giving it back to the first so that it continues exactly where it stopped. For that to work the system must save everything the process needs to continue and load the same for the next one. This is the context switch. It is the basic mechanism of multiprogramming and time sharing, and, since it does no useful work for any program, its cost sets the limit on how short a time slice can be. GATE asks for the steps, the triggers, the information saved and the CPU efficiency of a scheduler with a switching cost.

Prerequisites

You need the PCB and the process states from the process model; a context switch is the move between the Running and Ready states described there.

Precise definitions

Context. All the state of a process that must be restored for it to continue: the program counter, the processor status register, the general registers (and floating-point registers), the stack pointer, the memory-management state (the page table base register or the base and limit registers) and the kernel's record of it, which is the PCB.

Context switch. Saving the context of the running process in its PCB and loading the context of the next process from its PCB. It happens in kernel mode.

Steps (the animation follows exactly these):

  1. An interrupt or system call enters the kernel; the hardware saves the PC (and status) of the old process on the kernel stack.
  2. The kernel saves the old process's registers and other state in its PCB and changes its state (to Ready if preempted, to Waiting if it blocked, to Terminated if it ended).
  3. The scheduler chooses the next process.
  4. The kernel restores the new process: it loads its page table base (changing the address space) and its registers from its PCB, and sets its state to Running.
  5. A return from the interrupt resumes the new process at the saved program counter.

What triggers a context switch.

  • The timer interrupt ends the time slice (preemptive round robin, and generally preemptive scheduling).
  • The running process blocks (an I/O request, waiting for a lock, wait).
  • A higher-priority process becomes ready, for example when its I/O completes (preemptive priority scheduling).
  • The process yields the CPU voluntarily or terminates.

Dispatcher and scheduler. The scheduler decides which process runs next (a policy). The dispatcher is the part of the kernel that actually gives the CPU to that process: it does the context switch, switches to user mode and jumps to the right location. The time it takes from stopping one process to starting another is the dispatch latency.

Overhead. A context switch is pure overhead: no user program makes progress during it. Its time depends on the number of registers to save, the memory-management work (loading the page table pointer), and the indirect costs: cached translations and cache contents of the old process become useless for the new one. If the TLB is not tagged with a process id, it must be flushed at each switch and the new process starts with a cold TLB (TLB). Some hardware reduces the cost with several register sets, so that a switch only changes which set is current.

Mode switch versus context switch; process switch versus thread switch. A system call or an interrupt changes the mode but need not change the process. Switching between two threads of the same process leaves the address space unchanged, so no page-table change and no TLB flush is needed, which makes it cheaper than a switch between processes.

Efficiency with a time slice. If a round-robin system gives each process a time quantum qq and a context switch costs ss (and nothing else is lost), then

useful fraction=qq+s,overhead fraction=sq+s.\text{useful fraction} = \frac{q}{q + s}, \qquad \text{overhead fraction} = \frac{s}{q + s}.

A very small quantum makes the system responsive but spends most of the time switching; a very large one is efficient but approaches first-come first-served.

How it works

The first animation switches the CPU from process A to process B. Follow the PCBs (memory rows 100 to 105 for A and 200 to 205 for B): A's registers are copied out into its PCB one by one, A becomes Ready and B Running, the page table base register changes to B's page table, then B's saved registers are loaded and the return from interrupt starts B at its own saved PC.

A context switch from process A to process B: step 1

Machine run, not typed
running A(process A executing)
PC
3010
SP
7700
R0
21
R1
8
PTBR
7000
running
A
addrdecimalmeaning
064-PCB of A: PC
065-PCB of A: SP
066-PCB of A: R0
067-PCB of A: R1
0687000PCB of A: PTBR
069runningPCB of A: state
0C84120PCB of B: PC
0C98800PCB of B: SP
0CA55PCB of B: R0
0CB3PCB of B: R1
0CC9000PCB of B: PTBR
0CDreadyPCB of B: state

Step 1

Process A runs with PC = 3010, SP = 7700, R0 = 21, R1 = 8 and its page table at PTBR = 7000. Process B is READY: its saved state is in its process control block (PCB), here the six words at addresses 200 to 205. Each PCB holds the saved PC, SP, registers, the page table base and the state.

1 / 15
computed by script: an interpreter or machine simulation, one action per step. python3 scripts/gen-os-proc-traces.py

The second animation is a switch between two threads of the same process. Only the PC, SP and R0 are exchanged. The page table base register stays at 7000 throughout: that is why a thread switch is cheaper.

A switch between two threads of the same process: step 1

Machine run, not typed
running T1(thread T1 executing)
PC
5004
SP
63000
R0
7
PTBR
7000
running
T1
addrdecimalmeaning
064-TCB of T1: PC
065-TCB of T1: SP
066-TCB of T1: R0
067runningTCB of T1: state
06E5120TCB of T2: PC
06F61000TCB of T2: SP
07040TCB of T2: R0
071readyTCB of T2: state
12C7shared counter (global data)

Step 1

Two threads, T1 and T2, belong to ONE process. They share the code, the global data (here a counter, address 300, value 7), the heap, the open files and the page table (PTBR = 7000). Each has its own PC, registers and stack, saved in a thread control block (TCB).

1 / 9
computed by script: an interpreter or machine simulation, one action per step. python3 scripts/gen-os-proc-traces.py

Worked examples

EX 1How much of the CPU is useful?

Easy

Round robin, a context switch costing 1 ms after each quantum.

#include <stdio.h>
 
int main(void) {
    /* round robin with a context switch costing s ms after every quantum of q ms */
    double s = 1;
    double qs[4] = {1, 4, 10, 100};
    for (int i = 0; i < 4; i++) {
        double q = qs[i];
        printf("q = %5.0f ms, switch %.0f ms: %5.1f%% of the CPU time is useful, %5.1f%% is overhead\n", q, s, 100 * q / (q + s), 100 * s / (q + s));
    }
    /* a process needing 50 ms of CPU, quantum 10 ms: 5 quanta, the last one ends the process */
    int need = 50, q = 10;
    int slices = (need + q - 1) / q;
    printf("a %d ms burst with q = %d ms needs %d slices\n", need, q, slices);
    return 0;
}
q =     1 ms, switch 1 ms:  50.0% of the CPU time is useful,  50.0% is overhead
q =     4 ms, switch 1 ms:  80.0% of the CPU time is useful,  20.0% is overhead
q =    10 ms, switch 1 ms:  90.9% of the CPU time is useful,   9.1% is overhead
q =   100 ms, switch 1 ms:  99.0% of the CPU time is useful,   1.0% is overhead
a 50 ms burst with q = 10 ms needs 5 slices

Reading it. q/(q+s)q/(q + s): with q=sq = s half the machine is wasted; with q=100 sq = 100\ s about 1%. A quantum should be much larger than the switch time but small enough to give good response. The 50 ms burst needs ⌈50/10⌉=5\lceil 50/10 \rceil = 5 slices.

EX 2What does a context switch save?

Easy

The program counter, the stack pointer and the general and status registers go into the PCB. Memory-management information (the page table pointer) is switched too: the new process gets its own. The contents of memory (code, data, heap, stack) are not copied: each process's memory stays where it is, and only the pointer to it changes. Copying memory at each switch would take milliseconds, thousands of times longer than the few microseconds a real switch takes.

EX 3How many switches?

Medium

Three processes of 30 ms of CPU each run by round robin with quantum 10 ms, all ready at time 0, in the order P1, P2, P3. Each needs 3 quanta, so there are 9 slices in the order P1 P2 P3 P1 P2 P3 P1 P2 P3. A switch happens between consecutive slices: 8 switches (counting the start from idle and the end after the last slice as free). If a question counts a switch from the scheduler's start to the first process or after the last process, read its convention; the usual count for nn slices is n−1n - 1. With switch cost s=1s = 1 ms the total is 90+8=9890 + 8 = 98 ms, and the last process finishes at 98 ms.

EX 4A switch caused by an I/O completion

Medium

P1 (low priority) is running. The disk interrupt arrives for P2 (high priority) which has been waiting: the interrupt handler moves P2 from Waiting to Ready. If the scheduler is preemptive and priority-based, it compares priorities, finds P2 higher, and a context switch to P2 follows at once; P1 goes to Ready. If the scheduler is non-preemptive, P1 keeps the CPU until it blocks or ends, even though P2 is ready. The same event gives a switch or none, depending only on the scheduling policy.

EX 5Process switch against thread switch

GATE level

A switch between two processes loads a new page table base register; a TLB without process tags must be flushed, and the new process then takes a TLB miss on its first accesses. A switch between two threads of the same process does neither. Suppose a process switch costs 6 μ\mus directly plus 20 TLB misses of 0.1 μ\mus each afterwards (2 μ\mus), and a thread switch costs 3 μ\mus: the process switch is 8 μs8\ \mu\text{s} against 3 μs3\ \mu\text{s}, about 2.7 times as expensive, and the gap is larger once cache contents are counted. The ratio is the main reason threads were invented. (The numbers are an illustration, not measurements.)

Cheat box

Cheat box

  • Context == PC, registers, status, stack pointer, memory-management state (page table pointer), kept in the PCB.
  • Switch == save old context in PCB, choose next (scheduler), load new context and page table, resume (dispatcher).
  • Triggers: timer interrupt, blocking call, I/O completion that wakes a higher-priority process, yield, exit.
  • Pure overhead; no program progresses. Memory contents are not copied, only the pointer changes.
  • Round robin efficiency =q/(q+s)= q/(q + s); nn slices give n−1n - 1 switches between them.
  • Thread switch (same address space) is cheaper than a process switch (no page-table change, no TLB flush).
  • Dispatch latency == time to stop one process and start another.

Traps and GATE patterns

Connections

The PCB and states being switched are in the process model and process states. The choice of who runs next is the round-robin and priority scheduler. A system call is a mode switch; a thread switch avoids the address-space change; the cost of the translation cache after a switch is the topic of the TLB.

PYQs

5 previous year questions from your book. I re-solved each one myself (2 by running or simulating, 3 by reasoning only); the book's key is shown next to my answer. All PYQs

GATE 2024 · MSQQ5 · page 295 of the book
Consider a process P running on a CPU. Which one
or more of the following events will always trigger a
context switch by the OS that results in process P
moving to a non-running state (e.g., ready, blocked)?
  • (a)P makes a blocking system call to read a block of data from the disk
  • (b)tries to access a page that is in the swap space, triggering a page fault
  • (c)An interrupt is raised by the disk to deliver data requested by some other process
  • (d)A timer interrupt is raised by the hardware OPERATING SYSTEMS
GATE 2023 · MSQQ12 · page 297 of the book
Which one or more of the following need to be
saved on a context switch from one thread (T1) of
a process to another thread (T2) of the same process
?
  • (a)Page Table base register
  • (b)Stack pointer
  • (c)Program Counter
  • (d)General purpose register
GATE 2022 · MCQ · 2 marksQ14 · page 297 of the book
Consider four processes P, Q, R, and S scheduled
on a CPU as per round robin algorithm with a time
quantum of 4 units. The processes arrive in the
order P, Q, R, S, all at time t = 0. There is exactly
one context switch from S to Q, exactly one context
switch from R to Q, and exactly two context
switches from Q to R. There is no context switch
from S to P. Switching to a ready process after the
termination of another process is also considered a
context switch. Which one of the following is NOT
possible as CPU  burst time (in time units) of these
processes?
  • (a)P = 4, Q = 10, R = 6, S = 2
  • (b)P = 2, Q = 9, R = 5, S = 1
  • (c)P = 4, Q = 12, R = 5, S = 4
  • (d)P = 3, Q = 7, R = 7, S = 3
GATE 2011 · MCQ · 1 markQ41 · page 302 of the book
Let the time taken to switch between user and
kernel modes of execution be t1 while the time
taken to switch between two processes be t2. Which
of the following is TRUE?
  • (a)(t1) > (t2)
  • (b)(t1) = (t2)
  • (c)(t1) < (t2)
  • (d)Nothing can be said about the relation between t1 and t2
GATE 2006 · MCQ · 1 markQ50 · page 304 of the book
Consider three CPU-intensive processes, which
require 10, 20 and 30 time units and arrive at times
0, 2 and 6, respectively. How many context
switches are needed if the operating system
implements a Shortest Remaining Time First
(SRTF) scheduling algorithm?

Do not count the context switches at time zero and
at the end.
  • (a)1
  • (b)2
  • (c)3
  • (d)4

Self-check

Question 1

A quantum of 20 ms and a context switch of 2 ms. What fraction of the CPU does useful work?

Show answer

20/22=90.9%20/22 = 90.9\%.

Question 2

Why does a context switch change the page table base register?

Show answer

The new process has its own address space, so the memory-management hardware must translate addresses with the new process's page table.

Question 3

Name three events that can cause a context switch.

Show answer

A timer interrupt ending the quantum, the running process blocking for I/O, and an I/O completion waking a higher-priority process (also yield and termination).

Question 4

Two threads of one process are switched. Which of PC, SP, page table base register, general registers change?

Show answer

PC, SP and the general registers change. The page table base register does not.

Revision card

One-screen revision

  • Save old context in its PCB, choose next, load new context and page table, resume.
  • Triggers: timer, block, wake of higher priority, yield, exit.
  • Pure overhead; efficiency q/(q+s)q/(q + s); nn slices, n−1n - 1 switches.
  • Process switch changes address space (TLB flush); thread switch does not.
  • Scheduler chooses, dispatcher switches.

References

  • ·Silberschatz, Galvin, Gagne, Operating System Concepts, Chapter 3 Processes (context switch) and Chapter 5 CPU Scheduling (dispatcher)
  • ·Tanenbaum and Bos, Modern Operating Systems, Chapter 2 Processes and Threads (implementation of processes, scheduling)
  • ·Stallings, Operating Systems: Internals and Design Principles, Chapter 3 Process Description and Control (process switching)

Verification

The round-robin efficiency table is produced by the C program on this page (npm run verify:c) and by exact fractions in scripts/enum-checks/os_proc.py. The two animations are runs of a teaching machine (scripts/gen-os-proc-traces.py) re-checked by tests/os-proc-traces.test.ts: the values saved in process A's PCB equal what the CPU held before the switch, process B's values are loaded exactly, and PTBR changes for the process switch and never for the thread switch. The register set, PCB layout and costs are an idealised model; real switches also save floating-point and vector state (often lazily), kernel stack pointers and other fields, and the cost depends on the hardware (TLB tagging, cache behaviour). Textbook chapter titles are from memory. SECOND PASS (2026-11-02, done by the assistant, not a human check): every Self-check question was solved before the printed answer was read and all agreed; the definitions, worked examples, cheat box and traps were read claim by claim and the numbers re-derived by hand. No defect found. Status raised to self-checked; verified needs a textbook or human check.

last verified: never