ENع
←Context switch
Lesson 09 · Processes and threads

The context switch and the timer interrupt

12 min11 steps5 questionsBeginner
About this lesson

Your computer runs far more programs than it has CPU cores, and they all seem to run at once. The trick is taking turns, many times a second. Follow two programs, A and B, sharing one CPU: a hardware timer interrupts A, the kernel saves A's registers, its scheduler picks B, loads B's saved registers and returns into B, which carries on exactly where it stopped. The next tick swaps them back, and A's count is never lost. It builds on fork, exec and wait from the kernel's side; the Linux lesson on processes and signals shows the commands that list these programs.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 9 · Interactive
01 / 11

Two programs, one CPU

Programs A and B both want to run, but there is one CPU, and a CPU runs one program at a time. To share it, the kernel lets them take turns, switching many times a second, so both seem to run at once.

program A   running   (has the CPU)
program B   ready     (waiting for a turn)

one CPU core runs one program at a time.
the kernel swaps them many times a second
so both seem to run together: time sharing.
Loading figure…
or ← →
Read the lesson step by step
  1. Two programs, one CPU

    Programs A and B both want to run, but there is one CPU, and a CPU runs one program at a time. To share it, the kernel lets them take turns, switching many times a second, so both seem to run at once.

    program A   running   (has the CPU)
    program B   ready     (waiting for a turn)
    
    one CPU core runs one program at a time.
    the kernel swaps them many times a second
    so both seem to run together: time sharing.
  2. Registers hold the place

    The CPU keeps a running program's place in its registers, small fast slots inside the chip. PC, the program counter, says where it is. SP points at its stack. R1 holds its counter. Copy these out, and you have saved the program.

    register  holds                       for A now
    PC        where the program is         A·L2  (line 2)
    SP        where its stack is           A
    R1        its working value (a)        41
    
    its memory stays put; only the registers move.
    (real CPUs have more: x86-64 has 16 general
     registers, RISC-V has 32)
  3. A runs at full speed

    A runs directly on the CPU in user mode. Line 2 adds one, so R1 goes from 41 to 42. The kernel is not running at all. So how does it ever get the CPU back from a program that never stops?

    program A:
      1  while (1)
      2      a = a + 1;
    
    line 2   R1 = 41 + 1 = 42
    mode     user
    kernel   not running: the CPU belongs to A
  4. The timer interrupt

    At boot the kernel started a hardware timer. On Linux it ticks 250 times a second by default, once every 4 ms. Each tick is an interrupt: the CPU must stop what it is doing, whatever the program wants.

    at boot (kernel mode):
      tell the CPU where the timer handler is
      start the timer (a privileged instruction)
    
    Linux tick rate HZ: 100, 250, 300 or 1000; default 250
    1 s / 250 = 4 ms between ticks
    
    tick!    the CPU is interrupted mid-program
  5. Trap: save A

    The interrupt traps into the kernel. In one move the CPU switches to kernel mode and runs the timer handler the kernel chose at boot. A's registers are saved in kernel memory: PC A·L2, SP A, R1 42.

    timer interrupt
      save A's registers    -> A's save area
      mode user -> kernel
      jump to the timer handler
    
    A's save area   PC A·L2   SP A   R1 42
    A is now paused, not finished
  6. The scheduler picks B

    The kernel now has the CPU, so it can choose. Its scheduler sees that A has had its turn and B is ready and waiting. It decides to switch to B. A goes from running to ready.

    scheduler   who should run next?
      A   just had its turn
      B   ready, waiting
    choice      B
    
    A   running -> ready
    (how the scheduler chooses is the next module)
  7. Switch: load B

    This is the context switch itself. The kernel copies B's saved registers back into the CPU: PC B·L2, SP B, R1 7. Those are exactly the values B had when it was last stopped.

    context switch
      A's registers   already saved   (R1 42)
      B's registers   save area -> CPU
    
    CPU now   PC B·L2   SP B   R1 7
    mode      still kernel
  8. Return into B

    The kernel runs return-from-trap. The CPU drops to user mode and carries on at PC, which now points into B. B adds one, so R1 goes from 7 to 8. B never notices it was stopped.

    return-from-trap
      mode kernel -> user
      jump to PC = B·L2
    
    program B:
      1  while (1)
      2      b = b + 1;
    line 2   R1 = 7 + 1 = 8
    B   ready -> running
  9. Next tick: back to A

    The next tick runs the same steps the other way: save B's registers (R1 8), load A's. A resumes on line 2 with R1 = 42, untouched, and adds one to make 43. Its count is never lost.

    4 ms later, tick!
      save B's registers   PC B·L2  SP B  R1 8
      scheduler picks A
      load A's registers   PC A·L2  SP A  R1 42
      return-from-trap -> user mode, back in A
    line 2   R1 = 42 + 1 = 43
  10. What a switch costs

    A switch is not free: on Linux one between processes takes about 3 to 4 microseconds. A 4 ms tick is 1000 times longer, so the programs keep almost all the time. Switching far more often would waste it.

    switch between processes   3-4 us   (Berkeley CS162, Linux)
    switch between threads     about 100 ns
    1996, 200 MHz CPU           about 6 us   (OSTEP, lmbench)
    
    one tick                   4 ms = 4000 us
    4000 us / 4 us            = 1000
    
    the cost also includes caches refilling
    with the new program's data
  11. Count your own switches

    Every switch is counted. A C program can ask with getrusage(): ru_nivcsw counts the times the kernel took the CPU away, and ru_nvcsw the times it gave it up itself. On Linux, /proc shows the same counts.

    a busy loop, then ask the kernel (C99, POSIX):
    
    #include <stdio.h>
    #include <sys/resource.h>
    
    int main(void) {
        volatile unsigned long a = 0;
        struct rusage ru;
        for (unsigned long i = 0; i < 300000000UL; i++)
            a = a + 1;                       /* never gives up the CPU */
        getrusage(RUSAGE_SELF, &ru);
        printf("switched out by the kernel: %ld\n", ru.ru_nivcsw);
        printf("gave up the CPU itself:     %ld\n", ru.ru_nvcsw);
        return 0;
    }
    
    Linux: grep ctxt_switches /proc/<pid>/status
    
    the timer, the save and the switch in Python:
    
    saved = {"A": None, "B": {"pc": "B·L2", "r1": 7}}  # kernel memory
    cpu = {"pc": "A·L2", "r1": 41}                     # A is on the CPU
    running, waiting = "A", "B"
    
    for tick in range(1, 4):
        cpu["r1"] += 1                 # the program runs: one add
        saved[running] = dict(cpu)     # timer interrupt: save its registers
        running, waiting = waiting, running  # the scheduler picks the other
        cpu = dict(saved[running])     # switch: load its saved registers
        print("tick", tick, "saved", waiting, saved[waiting]["r1"],
              "-> run", running, "from", cpu["r1"])
    
    prints:
    tick 1 saved A 42 -> run B from 7
    tick 2 saved B 8 -> run A from 42
    tick 3 saved A 43 -> run B from 8

Quiz Unlocks after the last step.