Sub topic 6
Context Switching and Its Cost
Assume you know basic CPU registers, interrupts, process states, and queues. This chapter explains how the operating system changes the process or thread using the CPU.
What a Context Switch Does
A context is the information needed to pause a running process or thread and continue it later. It includes the program counter, CPU registers, stack pointer, status flags, and scheduling information.
A context switch occurs when the CPU stops executing one runnable task and starts another. The kernel saves the old task's context in its process control block (PCB) or thread control block. It then loads the next task's saved context.
A typical switch follows these steps:
- A timer interrupt, system call, blocking operation, or higher-priority task causes entry into the kernel.
- The kernel saves the current register values and changes the task's state.
- The scheduler selects a task from the ready queue.
- The dispatcher loads the selected task's context.
- The CPU returns to user mode or kernel mode at the selected task's saved program counter.
Where the Cost Comes From
A context switch does no direct application work. Its time is overhead. The exact cost depends on the hardware, operating system, and whether the switch is between processes or threads.
| Source of overhead | Why it costs time |
|---|---|
| Register save and restore | Memory operations update control blocks |
| Scheduler and dispatcher work | The kernel examines and selects a task |
| Address-space change | Page-table state may need to change |
| Cache and TLB effects | The next task may not find useful cached translations or data |
A process switch often costs more than a thread switch within the same process. Threads share an address space, so the kernel may not need to change page-table state. However, both types still require register and stack changes.
Context-switch cost also reduces CPU time available to applications. If a quantum is very short, switches happen frequently. Responsiveness may improve, but overhead increases.
Common Errors
Do not count every interrupt as a context switch. An interrupt may be handled and then return to the interrupted task. Also, do not confuse waiting time with context-switch time. Waiting time measures how long a process remains in the ready queue; context-switch time is kernel overhead during a change of task.
Exercise
Exercise
Why can reducing the Round Robin time quantum improve response time but reduce total throughput?
Show answer
A smaller quantum lets waiting tasks run sooner, improving response time. It also causes more context switches, increasing overhead and leaving less CPU time for useful application work.