CPU Scheduling

FCFS, SJF, SRTF, priority, round robin, multilevel feedback queues and Linux's CFS/EEVDF — with Gantt charts, metrics and worked examples.

Intermediate 5 min readLesson 5 of 16 Interview Q&A

With more runnable threads than CPU cores, the scheduler decides which one runs next and for how long. The policy shapes how responsive your desktop feels, how much throughput a server gets, and whether low-priority work ever runs at all.

Goals and metrics

MetricDefinitionWho cares
Turnaround timeCompletion − arrivalBatch jobs
Waiting timeTime spent in the ready queueEveryone
Response timeFirst run − arrivalInteractive apps
ThroughputJobs completed per unit timeServers
CPU utilisation% of time the CPU is busyCost
FairnessEach job gets its share; no starvationMulti-user systems

These goals conflict: short time slices improve response time but add context-switch overhead and hurt throughput.

Preemptive schedulers can take the CPU away from a running thread (on a timer interrupt or when a higher-priority thread wakes). Non-preemptive ones wait until the thread blocks or yields. All modern general-purpose OSes are preemptive.

The classic algorithms

We'll use the same workload throughout (all arriving at time 0):

ProcessBurst time
P16
P28
P33
P42

First come, first served (FCFS)

Run in arrival order until done.

P1P2P3P406141719

Waiting times 0, 6, 14, 17 → average 9.25. Simple, but short jobs stuck behind long ones suffer: the convoy effect.

Shortest job first (SJF)

Run the shortest burst first. It's provably optimal for average waiting time.

P4P3P1P20251119

Waiting times P4 = 0, P3 = 2, P1 = 5, P2 = 11 → average 4.5. The catches: burst lengths aren't known in advance (they're estimated from history with exponential averaging), and long jobs can starve. The preemptive version, shortest remaining time first (SRTF), switches when a shorter job arrives.

Priority scheduling

Run the highest-priority thread. Starvation of low priorities is fixed by aging: gradually raising the priority of threads that have waited a long time.

Round robin (RR)

Each thread runs for a time quantum q, then goes to the back of the queue. With q = 3:

P1P2P3P4P1P2P2036911141719

Response time is good and fair, but turnaround is often worse than SJF. Choosing q matters:

  • q too large → it degenerates into FCFS.
  • q too small → too much time is spent context switching.
  • Rule of thumb: q should be larger than about 80% of CPU bursts; typical values are 1–100 ms.

Multilevel feedback queue (MLFQ)

How do you favour short, interactive jobs without knowing burst lengths? Learn from behaviour:

Queue 0 — highest priorityq = 8 msQueue 1q = 16 msQueue 2 — lowest priorityFCFS / long q
  1. New threads start in the top queue.
  2. A thread that uses its entire quantum is probably CPU-bound: move it down a level.
  3. A thread that blocks early (interactive, I/O-bound) stays high.
  4. Periodically boost everything back to the top, to prevent starvation and adapt to phase changes.

Variants of MLFQ were used by classic Unix, Windows and macOS.

How Linux does it: CFS → EEVDF

Linux's Completely Fair Scheduler (2007–2023) aimed to give every runnable thread an equal share of the CPU:

  • Each thread accumulates virtual runtime (vruntime): real CPU time scaled by its weight (the nice value −20…19 maps to weights).
  • The scheduler always runs the thread with the smallest vruntime, keeping threads in a red-black tree ordered by vruntime (O(log n)).
  • A thread that slept has a low vruntime, so it runs soon after waking — good for interactivity.

Since Linux 6.6, EEVDF (earliest eligible virtual deadline first) refines this with explicit latency targets. Real-time threads (SCHED_FIFO, SCHED_RR) always run ahead of normal ones.

Multiprocessor scheduling

  • Per-core run queues avoid a global lock; load balancing migrates threads between them.
  • Processor affinity — keep a thread on the same core so its caches stay warm (soft affinity), or pin it explicitly (taskset, hard affinity).
  • NUMA awareness — prefer cores near the thread's memory.
  • Gang scheduling — run cooperating threads together.

Summary table

AlgorithmPreemptive?StrengthWeakness
FCFSNoSimpleConvoy effect
SJFNoOptimal average waiting timeNeeds burst estimates; starvation
SRTFYesEven better average waiting timeStarvation; overhead
PriorityEitherExpresses importanceStarvation (fix with aging)
Round robinYesFair, responsiveContext-switch overhead; quantum tuning
MLFQYesAdapts without prior knowledgeMany parameters; can be gamed
CFS / EEVDFYesProportional fairness, O(log n)Complex
Key takeaways
  • The scheduler trades off turnaround, response time, throughput and fairness.
  • SJF/SRTF minimise average waiting time but need burst estimates and can starve jobs.
  • Round robin gives fairness; the quantum controls the overhead trade-off.
  • MLFQ learns which jobs are interactive by watching them use or give up the CPU.
  • Linux uses weighted fair scheduling (CFS → EEVDF) with per-core run queues.
Interview questions
QCompute average waiting time for RR with q = 2 for bursts 5, 3, 1 arriving at 0.medium

Schedule: P1 0–2, P2 2–4, P3 4–5, P1 5–7, P2 7–8, P1 8–9. Completion times: P1 = 9, P2 = 8, P3 = 5. Waiting = completion − burst: P1 = 4, P2 = 5, P3 = 4 → average 13/3 ≈ 4.33.

QWhat is priority inversion?hard

A high-priority task waits for a lock held by a low-priority task, which in turn is preempted by medium-priority tasks, so the high-priority task waits indefinitely. Fix: priority inheritance — the lock holder temporarily inherits the waiter's priority. (This bug famously reset the Mars Pathfinder lander in 1997.)