CPU Scheduling
A laptop has perhaps 8–16 CPU cores and runs a few thousand threads. Most of them are asleep, waiting for a key press, a network packet or a timer, but whenever more threads are ready than there are cores, the kernel's scheduler decides who runs next and for how long. It runs every time a thread blocks, wakes up, exits, or uses up its time slice (quantum), and on every core.
What a scheduler tries to optimise
| Goal | Meaning | Who cares |
|---|---|---|
| Throughput | Jobs finished per second | Batch servers, build farms |
| Turnaround time | Finish time − arrival time | Batch jobs |
| Waiting time | Time spent ready but not running | Everyone |
| Response time | Arrival → first time on the CPU | Interactive users |
| Fairness | Equal share for equal-priority threads | Multi-user systems |
These goals conflict. Short time slices make a desktop feel snappy but waste time on context switches (saving one thread's registers, loading another's, and cold caches). Long slices raise throughput but make the UI stutter.
Schedulers are preemptive when the kernel can take the CPU away from a running thread (on a timer interrupt or when a higher-priority thread wakes). Linux, Windows and macOS are all fully preemptive. Old Windows 3.x and classic Mac OS were cooperative: a program had to give the CPU back itself, and one stuck program froze everything.
The classic algorithms, simulated
The textbook algorithms are easiest to understand by running them. The program below takes the same four jobs (arrival time and CPU burst in milliseconds) and schedules them with FCFS (first come, first served), non-preemptive SJF (shortest job first) and Round Robin with a 3 ms quantum, then draws a text Gantt chart (one character per millisecond) and the average waiting time.
JOBS = [("A", 0, 8), ("B", 1, 4), ("C", 2, 9), ("D", 3, 5)] # name, arrival, burst
def fcfs(jobs):
t, out = 0, []
for name, arr, burst in sorted(jobs, key=lambda j: j[1]):
t = max(t, arr)
out.append((name, t, t + burst))
t += burst
return out
def sjf(jobs):
t, out, todo = 0, [], list(jobs)
while todo:
ready = [j for j in todo if j[1] <= t] or [min(todo, key=lambda j: j[1])]
job = min(ready, key=lambda j: (j[2], j[1]))
t = max(t, job[1])
out.append((job[0], t, t + job[2]))
t += job[2]
todo.remove(job)
return out
def round_robin(jobs, q):
t, out, queue = 0, [], []
left = {n: b for n, _, b in jobs}
pending = sorted(jobs, key=lambda j: j[1])
while pending or queue:
while pending and pending[0][1] <= t:
queue.append(pending.pop(0)[0])
if not queue:
t = pending[0][1]
continue
name = queue.pop(0)
run = min(q, left[name])
out.append((name, t, t + run))
t += run
left[name] -= run
while pending and pending[0][1] <= t: # new arrivals queue up before the preempted job
queue.append(pending.pop(0)[0])
if left[name]:
queue.append(name)
return out
def report(title, slices):
gantt = "".join(name * (end - start) for name, start, end in slices)
finish = {name: end for name, _, end in slices}
waits = [finish[n] - arr - burst for n, arr, burst in JOBS]
print(f"{title:<12}|{gantt}|")
print(f"{'':<12} waits {dict(zip([j[0] for j in JOBS], waits))} avg {sum(waits) / len(waits):.2f} ms")
report("FCFS", fcfs(JOBS))
report("SJF", sjf(JOBS))
report("RR (q=3)", round_robin(JOBS, 3))FCFS |AAAAAAAABBBBCCCCCCCCCDDDDD|
waits {'A': 0, 'B': 7, 'C': 10, 'D': 18} avg 8.75 ms
SJF |AAAAAAAABBBBDDDDDCCCCCCCCC|
waits {'A': 0, 'B': 7, 'C': 15, 'D': 9} avg 7.75 ms
RR (q=3) |AAABBBCCCDDDAAABCCCDDAACCC|
waits {'A': 15, 'B': 11, 'C': 15, 'D': 13} avg 13.50 ms
Reading the results:
- FCFS is simple and fair in order, but the long job
Amakes everyone behind it wait (the convoy effect). - SJF gives the lowest average waiting time of any non-preemptive policy, but it needs to know burst lengths in advance, and a stream of short jobs can starve a long one forever.
- Round Robin gives every job a turn quickly (good response time) at the cost of more switches. With a huge quantum it degenerates into FCFS; with a tiny one, overhead dominates.
Priority scheduling and aging
Real systems attach a priority to each thread. The scheduler always runs the highest-priority ready thread. Low-priority work can starve, so schedulers use aging: the longer a thread waits, the more its effective priority rises. In this simulation a smaller number means higher priority, and every tick a waiting job gains 1:
jobs = {"backup": [5, 3], "editor": [1, 2], "indexer": [4, 3], "shell": [2, 2]} # name: [priority, ticks left]
waited = {n: 0 for n in jobs}
timeline = []
for tick in range(10):
ready = [n for n in jobs if jobs[n][1] > 0]
if not ready:
break
best = min(ready, key=lambda n: (jobs[n][0] - waited[n], n)) # aging boosts long waiters
timeline.append(best)
jobs[best][1] -= 1
for n in ready:
waited[n] = 0 if n == best else waited[n] + 1
print("tick: " + " ".join(f"{t:<7}" for t in range(len(timeline))))
print("runs: " + " ".join(f"{n:<7}" for n in timeline))tick: 0 1 2 3 4 5 6 7 8 9
runs: editor editor shell indexer backup shell indexer backup indexer backup
Without aging, backup (priority 5) would only run once everything else had finished. Here it gets the CPU at tick
4 even though shell and indexer still have work left, because two ticks of waiting lifted it past them.
How Linux schedules: CFS and EEVDF
Linux gives normal threads (SCHED_OTHER) a nice value from −20 (greedy) to +19 (polite); each step is roughly
a 10 % change in CPU share. From 2007 to 2023 the Completely Fair Scheduler (CFS) tracked a virtual runtime
(vruntime) per thread: real CPU time divided by the thread's weight. The thread with the smallest vruntime, the
one that has had the least fair share, runs next. Since kernel 6.6 the EEVDF scheduler replaced CFS's pick rule
(it also considers how much CPU each thread is owed and a virtual deadline), but the weighted-vruntime idea remains.
Here is a toy CFS: three threads with different nice values, a 1 ms tick, always picking the smallest vruntime.
The weights are the real kernel table values for nice 0, 5 and −5:
WEIGHT = {-5: 3121, 0: 1024, 5: 335} # from the kernel's sched_prio_to_weight table
threads = {"game": -5, "editor": 0, "backup": 5}
vruntime = {name: 0.0 for name in threads}
ran = {name: 0 for name in threads}
for ms in range(60):
current = min(vruntime, key=lambda n: (vruntime[n], n))
ran[current] += 1
vruntime[current] += 1 * 1024 / WEIGHT[threads[current]] # 1 ms of real time, scaled by weight
total_w = sum(WEIGHT[v] for v in threads.values())
for name, nice in threads.items():
print(f"{name:<7} nice {nice:>2}: ran {ran[name]:>2} ms of 60 "
f"(ideal share {60 * WEIGHT[nice] / total_w:4.1f}), vruntime {vruntime[name]:.1f}")game nice -5: ran 41 ms of 60 (ideal share 41.8), vruntime 13.5
editor nice 0: ran 14 ms of 60 (ideal share 13.7), vruntime 14.0
backup nice 5: ran 5 ms of 60 (ideal share 4.5), vruntime 15.3
The vruntimes end up nearly equal: that is what "fair" means. The nice −5 thread got about 9× the CPU of the nice +5 one because its vruntime clock ticks 9× slower.
On a real Linux system you set the nice value with nice (start) or renice (running). Lowering niceness (raising
priority) needs root; raising it does not:
echo "default niceness: $(nice)"
nice -n 10 nice
nice -n 10 sh -c 'echo "inside: $(nice)"; nice -n 5 nice'default niceness: 0
10
inside: 10
15
nice with no command prints the current niceness. nice -n 10 adds 10 to it, and the child inherits the value,
so a second nice -n 5 inside reaches 15.
Linux also has real-time policies (SCHED_FIFO, SCHED_RR, priority 1–99) that always beat normal threads, and
SCHED_DEADLINE. chrt -p PID shows a thread's policy, chrt -f 50 cmd starts one under FIFO (as root), and
taskset -c 0,1 cmd pins it to cores 0 and 1.
How Windows schedules: 32 priority levels
Windows uses a preemptive, priority-driven round robin over 32 levels: 0 (the zero-page thread), 1–15 the dynamic range for ordinary programs, 16–31 the real-time range. A thread's base priority comes from its process's priority class plus a relative thread priority:
| Priority class | Base level | start switch |
|---|---|---|
| Idle | 4 | /low |
| Below normal | 6 | /belownormal |
| Normal | 8 | /normal |
| Above normal | 10 | /abovenormal |
| High | 13 | /high |
| Realtime | 24 | /realtime (needs admin) |
Within the dynamic range Windows boosts priorities temporarily: a thread that finishes waiting for I/O, the thread owning the foreground window and a thread starved for about 4 seconds all get bumps, which then decay back. The quantum is short on client editions (about 2 clock ticks, ~30 ms) and longer on Server editions (12 ticks), and the foreground app's quantum can be stretched (Adjust for best performance of: Programs in System Properties).
C:\Users\ada>start "" /belownormal /affinity 3 notepad.exePS C:\Users\ada> $p = Get-Process notepad # sample output — yours will differ
PS C:\Users\ada> $p.PriorityClass = 'BelowNormal'
PS C:\Users\ada> $p | Select-Object Name, PriorityClass, BasePriority, ProcessorAffinity
Name PriorityClass BasePriority ProcessorAffinity
---- ------------- ------------ -----------------
Notepad BelowNormal 6 3ProcessorAffinity is a bit mask: 3 = binary 11 = cores 0 and 1, the same idea as Linux's taskset.
| Linux | Windows | |
|---|---|---|
| Normal policy | EEVDF (CFS before 6.6), weighted vruntime | Priority round robin with boosts |
| Priority range | nice −20 … +19; RT 1–99 | 1–15 dynamic, 16–31 real-time |
| Set priority | nice, renice, chrt |
start /high, Task Manager, PriorityClass |
| CPU pinning | taskset, cgroup cpusets |
start /affinity, ProcessorAffinity, Job objects |
| Hybrid CPUs (P/E cores) | Capacity-aware scheduling, Intel ITD | Thread Director hints, EcoQoS |
Learn more: Threads · Synchronization & Deadlocks · Mini Project: Scheduler & Memory Simulator
Test yourself
Which algorithm minimises average waiting time among non-preemptive policies but can starve long jobs?
- FCFS
- Shortest Job First
- Round Robin
- Lottery scheduling
In Linux's CFS, which thread runs next?
- The one with the highest nice value
- The one that arrived first
- The one with the smallest virtual runtime
- A random one
What base priority does a thread in a Windows Normal-priority-class process start from?
- 0
- 8
- 15
- 24