PCSPR1KERNELPCB·L2SPBR174 msCPUPCA·L2SPAR141MODEuser1while (1)2 a = a + 1;1while (1)2 b = b + 1;RUNB
Back: kernel memory (saved registers) and the kernel with its schedulerMiddle: the timer, the CPU, its registers and mode; front: programs A and BTokens: a timer tick, registers saved and loaded, the RUN marker movingAt the back, kernel memory: A's saved registers, the kernel with its scheduler, and B's saved registers. In the middle, the timer wired to the CPU, the CPU's registers (PC, SP, R1) and its mode. In front, programs A and B; RUN marks the one on the CPU. A counts to 42. A tick traps into the kernel, A's registers are saved, the scheduler picks B, B's saved registers are loaded and return-from-trap resumes B, which counts 7 to 8. The next tick switches back and A goes on from 42. The figure shows one save area per program. Real kernels save twice: the trap saves the program's user registers on its kernel stack, and the switch routine saves the kernel's own registers in the process structure (OSTEP Figure 6.3; in xv6, the trapframe and p->context).

Taking turns

  1. 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.

The switch

Why it works

What happens

;; step 1/11 · two-programs
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.

The figure shows one save area per program. Real kernels save twice: the trap saves the program's user registers on its kernel stack, and the switch routine saves the kernel's own registers in the process structure (OSTEP Figure 6.3; in xv6, the trapframe and p->context). PC is shown as a program and a line (A·L2). In a real CPU it holds the memory address of the next machine instruction, and one line of C is several instructions.