Operating Systems Module 2: Processes and threads Lesson 2.5 12 min

Context switching

How the kernel takes the CPU from one process and gives it to another: save the registers, pick the next one, load its registers, and carry on.

You are typing in a document while music plays and a download runs. One core, three programs. Each of them is stopped and restarted many times a second, and none of them ever notices. How can the kernel stop a program in the middle of an instruction stream and bring it back later, exactly as it was?

The trick is that everything about a running program that the CPU holds fits in a handful of registers. Copy those somewhere safe, and the program can be put back at any time. This is a context switch.

What a context switch does

The context of a process is the state the CPU holds for it: the program counter (PC), the stack pointer (SP) and the general registers. A context switch swaps one context for another. The steps are always the same:

  1. Something makes the kernel take over: a timer interrupt (Lesson 1.2) or a system call (Lesson 1.3).
  2. The kernel saves the running process’s registers into its PCB (Lesson 2.2).
  3. The scheduler picks the next process (Module 3 is about how).
  4. If the next process belongs to a different address space, the kernel switches to it.
  5. The kernel loads the next process’s registers from its PCB.
  6. It returns from the interrupt, and the CPU carries on in user mode from the program counter it just loaded.

Step through it. P1 is running and P2 is ready. The CPU is the dark box in the middle, and the two PCBs are on either side. Watch the values move between them.

P1 is switched out, P2 is switched in

  1. P1 is running P1 is on the CPU. The CPU's registers hold P1's values: the program counter (PC) says which instruction comes next, and the stack pointer (SP) says where P1's stack is. P2 is ready, waiting for its turn: its values are stored in its PCB.
    Running
    P1
    CPU mode
    user
    CPU PC
    0x401a2c
    P1 PCB PC
    not saved yet
    P2 PCB PC
    0x402b10
    Address space in use
    page table A
  2. The timer interrupt fires P1 has used up its time slice, so the timer interrupt fires (Lesson 1.2). The CPU switches to kernel mode and jumps to the kernel's interrupt handler. P1's registers have not been touched yet: they are still in the CPU.
    Running
    P1
    CPU mode
    kernel
    CPU PC
    0x401a2c
    P1 PCB PC
    not saved yet
    P2 PCB PC
    0x402b10
    Address space in use
    page table A
  3. Save P1's registers into its PCB The kernel copies the CPU's registers into P1's PCB, including the PC and SP. This is the whole trick: everything P1 needs in order to carry on later is now in memory, so the CPU is free. P1 moves from running to ready.
    Running
    none (kernel)
    CPU mode
    kernel
    CPU PC
    0x401a2c
    P1 PCB PC
    0x401a2c
    P2 PCB PC
    0x402b10
    Address space in use
    page table A
  4. The scheduler picks P2 The scheduler (Module 3) looks at the ready processes and chooses P2. How it chooses is a separate question. A context switch is the mechanism that makes the choice happen.
    Running
    none (kernel)
    CPU mode
    kernel
    CPU PC
    0x401a2c
    P1 PCB PC
    0x401a2c
    P2 PCB PC
    0x402b10
    Address space in use
    page table A
  5. Switch to P2's address space P2 is a different process, so it has its own address space. The kernel points the CPU at P2's page table (page table B). The CPU's cache of address translations, the TLB, still holds P1's entries, which are useless for P2. The kernel has to clear them, or tag them, or accept slower memory accesses for a while.
    Running
    none (kernel)
    CPU mode
    kernel
    CPU PC
    0x401a2c
    P1 PCB PC
    0x401a2c
    P2 PCB PC
    0x402b10
    Address space in use
    page table B
  6. Load P2's registers from its PCB The kernel copies P2's saved values into the CPU: its PC, SP and the general registers. P2 moves from ready to running.
    Running
    P2
    CPU mode
    kernel
    CPU PC
    0x402b10
    P1 PCB PC
    0x401a2c
    P2 PCB PC
    0x402b10
    Address space in use
    page table B
  7. Return from the interrupt The kernel runs its return-from-interrupt instruction. The CPU goes back to user mode and carries on from the PC it just loaded.
    Running
    P2
    CPU mode
    user
    CPU PC
    0x402b10
    P1 PCB PC
    0x401a2c
    P2 PCB PC
    0x402b10
    Address space in use
    page table B
  8. P2 carries on exactly where it stopped P2 runs the very next instruction after the one it was on when it was last taken off the CPU. From P2's point of view nothing happened: it was never told it had been stopped. P1 is waiting in the ready state with its values saved, and will come back the same way.
    Running
    P2
    CPU mode
    user
    CPU PC
    0x402b14
    P1 PCB PC
    0x401a2c
    P2 PCB PC
    not saved yet
    Address space in use
    page table B

The key moments are “Save P1’s registers into its PCB”, where P1’s PC and the other registers are copied into memory, and “Load P2’s registers from its PCB”, where P2’s are copied out. Everything else is bookkeeping around it. Because P1’s values were saved, the same thing can happen the other way round later: P1’s registers go back into the CPU, and P1 resumes at the saved PC, as if it had never left.

The extra step for a different process

The extra step in the process switch, “Switch to P2’s address space”, changed the page table: the map that tells the CPU how this process’s addresses correspond to real memory (Module 6). Every process has its own address space (Lesson 2.1), so switching to a different process means switching to its map. That has a cost, because the CPU keeps a small cache of recent address translations called the TLB, and the entries in it belong to the old process. The kernel has to clear them, or tag each one with its owner, or let the new process start slow.

Two threads of the same process share one address space. Switching between them skips that step.

The same switch between two threads of one process

  1. P1 is running P1 is on the CPU. The CPU's registers hold P1's values: the program counter (PC) says which instruction comes next, and the stack pointer (SP) says where P1's stack is. P2 is ready, waiting for its turn: its values are stored in its PCB.
    Running
    P1
    CPU mode
    user
    CPU PC
    0x401a2c
    P1 PCB PC
    not saved yet
    P2 PCB PC
    0x402b10
    Address space in use
    page table A
  2. The timer interrupt fires P1 has used up its time slice, so the timer interrupt fires (Lesson 1.2). The CPU switches to kernel mode and jumps to the kernel's interrupt handler. P1's registers have not been touched yet: they are still in the CPU.
    Running
    P1
    CPU mode
    kernel
    CPU PC
    0x401a2c
    P1 PCB PC
    not saved yet
    P2 PCB PC
    0x402b10
    Address space in use
    page table A
  3. Save P1's registers into its PCB The kernel copies the CPU's registers into P1's PCB, including the PC and SP. This is the whole trick: everything P1 needs in order to carry on later is now in memory, so the CPU is free. P1 moves from running to ready.
    Running
    none (kernel)
    CPU mode
    kernel
    CPU PC
    0x401a2c
    P1 PCB PC
    0x401a2c
    P2 PCB PC
    0x402b10
    Address space in use
    page table A
  4. The scheduler picks P2 The scheduler (Module 3) looks at the ready processes and chooses P2. How it chooses is a separate question. A context switch is the mechanism that makes the choice happen.
    Running
    none (kernel)
    CPU mode
    kernel
    CPU PC
    0x401a2c
    P1 PCB PC
    0x401a2c
    P2 PCB PC
    0x402b10
    Address space in use
    page table A
  5. Load P2's registers from its PCB The kernel copies P2's saved values into the CPU: its PC, SP and the general registers. P2 moves from ready to running. P2 is a thread of the same process as P1, so the address space did not change: the page table stays the same and the TLB is still full of useful entries.
    Running
    P2
    CPU mode
    kernel
    CPU PC
    0x402b10
    P1 PCB PC
    0x401a2c
    P2 PCB PC
    0x402b10
    Address space in use
    page table A
  6. Return from the interrupt The kernel runs its return-from-interrupt instruction. The CPU goes back to user mode and carries on from the PC it just loaded.
    Running
    P2
    CPU mode
    user
    CPU PC
    0x402b10
    P1 PCB PC
    0x401a2c
    P2 PCB PC
    0x402b10
    Address space in use
    page table A
  7. P2 carries on exactly where it stopped P2 runs the very next instruction after the one it was on when it was last taken off the CPU. From P2's point of view nothing happened: it was never told it had been stopped. P1 is waiting in the ready state with its values saved, and will come back the same way.
    Running
    P2
    CPU mode
    user
    CPU PC
    0x402b14
    P1 PCB PC
    0x401a2c
    P2 PCB PC
    not saved yet
    Address space in use
    page table A

A thread switch has one step fewer, and more importantly it does not throw away the TLB’s useful entries. That is why switching threads of one process is cheaper than switching between processes. Press Try it to flip between the two cases.

The cost of switching

A context switch is pure overhead: while the kernel does it, no user program is making progress. It has two costs:

  • the direct cost: saving and loading registers, and running the scheduler;
  • the indirect cost: the new process finds the CPU’s caches and the TLB full of the old one’s data, so it runs slower for a while.

This is why a scheduler cannot simply switch as often as possible. A switch every microsecond would leave no time for real work. How often to switch is a central question of Module 3.

Why a switch happens

There are two kinds, and Linux counts them separately:

  • A voluntary switch happens when a process gives up the CPU itself: it calls sleep, waits for input, or waits for a lock. It has nothing to do, so the CPU should go to someone else.
  • An involuntary switch happens when the kernel takes the CPU away: the timer fired and the time slice is over, or a more important process became ready.

This program sleeps 20 times, which gives up the CPU each time, and reads its own counts with getrusage:

switches.c
#include <stdio.h>
#include <unistd.h>
#include <sys/resource.h>

int main(void) {
    struct rusage before, after;
    getrusage(RUSAGE_SELF, &before);
    for (int i = 0; i < 20; i++) usleep(1000);     /* 20 times: give up the CPU and wait */
    getrusage(RUSAGE_SELF, &after);
    long voluntary = after.ru_nvcsw - before.ru_nvcsw;
    printf("voluntary switches while sleeping 20 times: at least 20? %s\n", voluntary >= 20 ? "yes" : "no");
    printf("voluntary %ld, involuntary %ld (whole run so far)\n", after.ru_nvcsw, after.ru_nivcsw);
    return 0;
}

Output (one run)

voluntary switches while sleeping 20 times: at least 20? yes
voluntary 20, involuntary 0 (whole run so far)

Every sleep was a voluntary switch. The involuntary count depends on how busy the machine is: a program that is alone on an idle machine may never be pre-empted, and one that competes with many others will be, often.

In the real world

On Linux you can watch context switches live:

Terminal
$ vmstat 1
$ pidstat -w 1
$ grep ctxt /proc/self/status

vmstat 1 prints one line per second, and its cs column is the number of context switches in that second across the whole machine. pidstat -w 1 (from the sysstat package) shows cswch/s for voluntary and nvcswch/s for involuntary switches, per process. The /proc/PID/status file has voluntary_ctxt_switches and nonvoluntary_ctxt_switches counters.

A process with many voluntary switches is mostly waiting, for example a web server waiting for requests. A process with many involuntary switches wants more CPU than it is getting, which usually means the machine is overloaded. You will use exactly this clue in the capstone. :::

Quick check

Quick check

  1. What does the kernel save when it switches a process off the CPU?
  2. Why does switching to a different process cost more than switching to another thread of the same process?
  3. A program calls sleep and the kernel runs someone else. Is that a voluntary or an involuntary switch?
  4. After a context switch, process P2 continues. From which point does it continue?

Review: what you learned earlier

Coming back to an idea after a break is what makes it stick. These questions come from earlier modules, starting with any you missed. Answer from memory before you look anything up.

Spaced review

This review picks questions for you, so it needs JavaScript.

Module 2 recap

You now know what a process is: a running program with its own address space of text, data, heap and stack, described by a PCB and always in one of five states. You have seen how Unix creates them with fork, exec and wait, what zombies and orphans are, how threads share an address space while keeping their own stacks and registers, and how a context switch saves one set of registers and loads another so the CPU can be shared.

Next, Module 3: the kernel can switch processes, but which one should run next? You will compare first come first served, shortest job first, round robin and priorities, and see why the answer is never simply “the fastest”.

Your progress is saved in this browser. Sign in to keep it on every device. Free, no password.

Join the discussion