The context switch and the timer interrupt
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
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.
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.
اقرأ الدرس خطوة بخطوة
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.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)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 AThe 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-programTrap: 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 finishedThe 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)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 kernelReturn 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 -> runningNext 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 = 43What 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 dataCount 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
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01Program A runs a loop that never makes a system call. How does the kernel ever get the CPU back?
The timer interrupt fires whatever the program is doing. Like any trap it switches the CPU to kernel mode and runs the handler the kernel chose at boot, so the kernel is back in control.
02What must the kernel save so that A can later carry on exactly where it stopped?
A's memory stays where it is. Its place on the CPU is only the values in the registers, so saving and later reloading them resumes A at the same line with the same values.
03In the figure, A had R1 = 42 when it was switched out. B then ran for a while. What is A's R1 when it runs again?
B did use the same register, but the kernel saved A's 42 first and loads it back on the switch to A. A then adds one and gets 43.
04On Linux a switch between processes takes about 3 to 4 microseconds and the default tick is 4 ms. About how many times longer is a tick than a switch?
4 ms is 4000 microseconds, and 4000 / 4 = 1000. The programs keep almost all of the CPU time; switching much more often would waste a bigger share.
05getrusage() reports ru_nivcsw, involuntary context switches. Which of these is one?
Involuntary means the kernel took the CPU away, after a timer tick showed the time slice was used up or a higher-priority program became ready. Waiting for input is a voluntary switch, counted in ru_nvcsw.
المسرد
- Register
- A small, very fast storage slot inside the CPU. A running program keeps its working values in registers.
- Program counter (PC)
- The register that holds where the program is: the address of the next instruction to run.
- Stack pointer (SP)
- The register that points at the top of the program's stack, where function calls keep their local data.
- Timer interrupt
- A signal from a hardware timer that stops the CPU every tick and traps into the kernel, so the kernel regains control.
- Context switch
- Saving the registers of the running program and loading the saved registers of another, so the CPU carries on with the other one.
- Scheduler
- The part of the kernel that decides which ready program runs next and for how long.
- Time slice
- How long a program may run before the scheduler may switch to another. The timer tick is when the kernel usually checks it.
- Return-from-trap
- The instruction that leaves the kernel: it switches the CPU back to user mode and jumps to the saved program counter.
الملاحظات والمصادر
- 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.
- Linux does not switch on every tick: the tick lets the scheduler check whether the running program has used up its time slice, which is often several ticks long. Kernels built with NO_HZ also stop the tick on idle CPUs. 250 Hz is the default; 100, 300 and 1000 are the other choices.
- A program also gives up the CPU by itself when it waits, for example for a key press or a disk read. That is a voluntary switch (ru_nvcsw); a switch forced by the timer is involuntary (ru_nivcsw).
- The counts the C program prints depend on how busy the machine is. If nothing else wants that CPU core, the kernel has no reason to switch, and ru_nivcsw can be close to zero.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 6: Limited Direct Execution
- Berkeley CS162, Lecture 7: Synchronization 1 (context switch details and costs)
- MIT 6.1810 (2024), lecture notes: Thread switching
- Linux source: kernel/Kconfig.hz (timer frequency, default 250 Hz)
- Linux kernel documentation: NO_HZ, reducing scheduling-clock ticks
- Linux man-pages: getrusage(2)
- Linux man-pages: proc_pid_status(5)
اختبار يتاح بعد الخطوة الأخيرة.