Operating-System Kernels

the process scheduler

A computer has only a handful of CPU cores, yet hundreds of processes and threads all want to run. The process scheduler is the part of the kernel that decides, moment to moment, which task gets a CPU and for how long - the traffic controller that creates the illusion that everything is running at once by rapidly switching the CPU among them. Without it, one program could hog a core forever; with it, the browser, the music player, and the compiler all make progress on the same few cores.

Here is the core machinery. Tasks that are ready to run (not blocked waiting for disk or network) sit in a run queue. The scheduler picks one, sets a timer, and lets it run for a time slice (a small slice of CPU time, often a few milliseconds). When the slice expires, the timer interrupt fires, the scheduler saves that task's registers and state (a context switch) and loads another task's - so they take turns. Tasks also yield the CPU voluntarily when they block (calling read() that has no data yet, say). Priority and the nice value let you bias these decisions: a 'nicer' process (higher nice number) is more willing to yield CPU to others, a low-priority one gets less. A preemptive scheduler can forcibly take the CPU away from a running task when something more deserving should run, rather than waiting for it to give it up - which is what keeps one runaway loop from freezing your machine.

Why it matters and a key honesty point: scheduling is the heart of how an OS feels - good scheduling means a responsive interactive system even under heavy load, bad scheduling means stutter and lag. But there is no single 'best' schedule; it is a balancing act between conflicting goals - throughput (total work done), latency (how quickly an interactive task responds), and fairness (no task starved) - and you cannot maximize all at once. That is exactly why kernels keep refining their scheduling algorithms, like Linux's Completely Fair Scheduler and its successor EEVDF.

run queue: [browser, compiler, music]. scheduler runs browser for one time slice -> timer interrupt -> context switch saves browser regs, loads compiler -> ... A preemptive scheduler can yank a runaway loop off the CPU mid-run.

The scheduler rotates ready tasks through the CPU via time slices and context switches; preemption stops any one task from hogging a core.

There is no universally optimal schedule: throughput, latency, and fairness genuinely conflict, so every scheduler picks trade-offs rather than a perfect answer. Also, 'nice' is counterintuitive - a HIGHER nice value means LOWER priority (the process is being nice and yielding), which trips up many beginners.

Also called
process/thread schedulertask schedulerCPU scheduler排程器