CPU Scheduling (OS Core #3)
The scheduler decides which ready thread runs next. Every algorithm is a different answer to “next”, and every exam question is the same arithmetic on a Gantt chart. Learn the four numbers — arrival, burst, completion, waiting — and the rest is bookkeeping.
Scheduling goals and metrics
A scheduler cannot optimise everything at once. The usual goals conflict:
- CPU utilisation: keep the CPU busy (target 100%, realistic 70–90% on servers).
- Throughput: jobs completed per second.
- Turnaround time: arrival to completion. Batch systems care about this.
- Waiting time: time spent ready but not running.
- Response time: arrival to first run. Interactive systems care about this.
- Fairness: no thread starves.
- Overhead: the scheduler itself should be cheap.
For a job that arrives at time \(a\), finishes at \(c\), and needs \(b\) units of CPU:
\[ T_{\text{turnaround}} = c - a, \qquad T_{\text{waiting}} = T_{\text{turnaround}} - b, \qquad T_{\text{response}} = c_{\text{first run}} - a \]
For a run of \(n\) jobs, report the averages. In a non-preemptive scheduler, a job that starts runs to completion, so response time equals waiting time. Under preemption they differ, and that difference is the point of round robin.
turnaround and waiting times?
ASolution
Turnaround is \(12 - 3 = 9\). Waiting is \(9 - 5 = 4\): the job was ready for four units while other work ran.
Workload assumptions, and preemptive versus non-preemptive
Classical scheduling analysis assumes jobs are known in advance, CPU bursts are independent, and the cost of switching is zero. Real systems know none of that, so the algorithms below are approximations, and the exam versions are the clean version.
Non-preemptive: once a job starts, it runs until it blocks or finishes. Simple and low-overhead, but one long job can delay everyone (the convoy effect).
Preemptive: the scheduler can take the CPU away, usually on a timer tick or when a higher-priority job becomes ready. Needed for responsiveness and fairness, but every preemption costs a context switch (Ch. 2).
The timer interval sets the granularity. Linux used 250 Hz–1000 Hz ticks for years; modern kernels use a tickless design and let the scheduler decide when to interrupt.
ASolution
A CPU-bound job that never blocks would hold the CPU until it finishes. The timer interrupt is what forces it to give way so typing and UI updates stay responsive.
First Come, First Served (FCFS)
Run jobs in arrival order. Non-preemptive, trivial to implement, and terrible when one long job arrives first.
Example: P1 (arrive 0, burst 8), P2 (1, 4), P3 (2, 9), P4 (3, 5).
| Job | Start | Finish | Turnaround | Waiting |
|---|---|---|---|---|
| P1 | 0 | 8 | 8 | 0 |
| P2 | 8 | 12 | 11 | 7 |
| P3 | 12 | 21 | 19 | 10 |
| P4 | 21 | 26 | 23 | 18 |
Average waiting = 8.75, average turnaround = 15.25. P1’s 8 units block three short jobs, which is the convoy effect: short jobs queue behind a long one.
ASolution
Arrival order is unrelated to burst length. A long job that arrives first makes every later job wait, and the average is dominated by that one delay.
Shortest Job First (SJF)
Run the job with the smallest burst among those that have arrived. Non-preemptive. It is provably optimal for average waiting time when all jobs are available at once: put the shortest first, and every subsequent job waits less.
Same example: at \(t=0\) only P1 is present, so it runs 0–8. Then P2 (4), P4 (5), P3 (9) run in that order.
| Job | Start | Finish | Turnaround | Waiting |
|---|---|---|---|---|
| P1 | 0 | 8 | 8 | 0 |
| P2 | 8 | 12 | 11 | 7 |
| P4 | 12 | 17 | 14 | 9 |
| P3 | 17 | 26 | 24 | 15 |
Average waiting = 7.75, better than FCFS. The catch is that burst length is not known in advance; real schedulers predict it from history (exponential averaging).
SJF can starve long jobs: a stream of short arrivals keeps pushing them back.
ASolution
For jobs all available at time 0, the sum of waiting times is minimised by ordering bursts shortest first. Any inversion (long before short) increases the total by the difference.
Shortest Remaining Time First (SRTF)
SRTF is SJF with preemption: at every arrival, compare the new job’s burst with the remaining time of the running job, and switch if the new one is shorter.
Same example:
- 0–1: P1 (remaining 7).
- 1: P2 arrives with 4 < 7 → switch.
- 1–5: P2, finishes.
- 5: P1 (7) vs P3 (9) vs P4 (5) → P4 runs 5–10.
- 10–17: P1 (7).
- 17–26: P3.
| Job | Finish | Turnaround | Waiting |
|---|---|---|---|
| P1 | 17 | 17 | 9 |
| P2 | 5 | 4 | 0 |
| P3 | 26 | 24 | 15 |
| P4 | 10 | 7 | 2 |
Average waiting = 6.5, the best of the four on this input. SRTF is optimal for average waiting time among preemptive policies when bursts are known. It has more context switches and still starves long jobs.
ASolution
The remaining burst of the running job, and a decision at every arrival. SJF only decides at job completion.
Priority scheduling
Each job has a priority; the highest runs first. Priorities can be static or dynamic, and preemptive or not.
The problem is starvation: a low-priority job may never run if higher-priority work keeps arriving. The standard fix is aging: increase a waiting job’s priority over time, so it eventually becomes the highest.
Windows and Linux both use dynamic priorities; nice values on Linux range from
-20 (highest) to 19 (lowest), with 0 as the default.
ASolution
A job’s priority rises the longer it waits. After a bounded time it outranks every newcomer, so it is scheduled.
Round Robin (RR)
FCFS with preemption and a time slice (quantum). Each job runs for at most \(q\) units, then goes to the back of the queue.
Same example with \(q = 3\):
| Job | Runs at | Finish | Turnaround | Waiting |
|---|---|---|---|---|
| P1 | 0–3, 12–15, 21–23 | 23 | 23 | 15 |
| P2 | 3–6, 15–16 | 16 | 15 | 11 |
| P3 | 6–9, 16–19, 23–26 | 26 | 24 | 15 |
| P4 | 9–12, 19–21 | 21 | 18 | 13 |
Average waiting = 13.5, worse than SJF on this input, but every job starts within 9 units. Response time is what RR optimises.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, minimum height=0.5cm, font=\scriptsize\bfseries}]
\foreach \x/\w/\lab in {0/3/P1,3/3/P2,6/3/P3,9/3/P4,12/3/P1,15/1/P2,16/3/P3,19/2/P4,21/2/P1,23/3/P3} {
\node[b, fill=blue!12, minimum width=\w cm] at (\x+\w/2,0) {\lab};
}
\draw[->, thick] (0,-0.45) -- (26,-0.45);
\foreach \x in {0,3,6,9,12,15,16,19,21,23,26} \draw (\x,-0.4) -- (\x,-0.5) node[below, font=\tiny] {\x};
\node[font=\scriptsize, anchor=north] at (13,-1.0) {quantum = 3: fair response, more switches};
\end{tikzpicture}
Quantum choice is the whole trade-off:
- \(q\) too large → RR degenerates into FCFS.
- \(q\) too small → context-switch overhead dominates. With \(q = 1\) ms and a 5 µs switch, about 0.5% of the CPU goes to switching; with 20 µs switches, 2%.
- Rule of thumb: make \(q\) large relative to the switch cost, but small enough that interactive requests get a turn quickly (10–100 ms).
until a process that just became ready gets its first turn?
ASolution
Up to 1 second, because it may wait behind all 100. That is why huge run queues hurt response time, and why real schedulers use priorities and shorter quanta.
Multilevel queue scheduling
Jobs are divided into classes with different policies. For example:
| Queue | Contents | Policy |
|---|---|---|
| System | kernel threads, daemons | highest priority, small quantum |
| Interactive | shell, editor | RR, 20 ms |
| Batch | compilers, backups | FCFS, long quantum |
A job stays in its queue, and the scheduler picks from the highest non-empty queue. The problem is rigidity: a CPU-bound job that becomes interactive stays punished.
Multilevel feedback queue (MLFQ) fixes that by letting jobs move between queues:
- New jobs start in the highest-priority queue.
- If a job uses its whole quantum, it moves down one level.
- If it blocks before using its quantum (interactive behaviour), it stays or moves up.
- A periodic boost moves everything back to the top, preventing starvation.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=3.4cm, minimum height=0.6cm, font=\scriptsize},
a/.style={->, thick}]
\node[b, fill=green!18] (q0) at (0,1.4) {Q0: RR, quantum 8};
\node[b, fill=orange!15] (q1) at (0,0.5) {Q1: RR, quantum 16};
\node[b, fill=red!12] (q2) at (0,-0.4) {Q2: FCFS};
\draw[a] (q0) -- node[right, font=\tiny] {used full quantum} (q1);
\draw[a] (q1) -- node[right, font=\tiny] {used full quantum} (q2);
\draw[a, dashed, blue!60] (q2) to[bend left=35] node[left, font=\tiny] {periodic boost} (q0);
\node[font=\scriptsize, anchor=west] at (2.1,0.5) {highest non-empty queue runs first};
\end{tikzpicture}
MLFQ is what most general-purpose schedulers approximate: it favours short, interactive jobs without starving CPU hogs.
ASolution
Without it, a CPU-bound job falls to the bottom queue and can starve as new short jobs keep arriving at the top.
Worked comparison
Same four jobs, all four policies:
| Policy | Avg waiting | Avg turnaround | Avg response | Starvation |
|---|---|---|---|---|
| FCFS | 8.75 | 15.25 | 8.75 | no |
| SJF | 7.75 | 14.25 | 7.75 | yes |
| SRTF | 6.50 | 13.00 | 4.25 | yes |
| RR (\(q=3\)) | 13.50 | 20.00 | 3.00 | no |
The table is the lesson: SJF/SRTF win on waiting, RR wins on response, and no single policy wins everything. Real schedulers blend them.
struct Job { int id, arrival, burst; };
// FCFS metrics: completion times follow arrival order
void fcfs(std::vector<Job> jobs) {
std::sort(jobs.begin(), jobs.end(),
[](const Job& a, const Job& b) { return a.arrival < b.arrival; });
long long t = 0, wait = 0, turn = 0;
for (const Job& j : jobs) {
t = std::max<long long>(t, j.arrival) + j.burst;
turn += t - j.arrival;
wait += t - j.arrival - j.burst;
}
std::printf("avg wait %.2f, avg turnaround %.2f\n",
double(wait) / jobs.size(), double(turn) / jobs.size());
}
The same loop handles SJF if the input is already sorted by burst; SRTF and RR need an event loop with a ready queue.
response time?
ASolution
Jobs are interrupted and requeued, so each waits behind others repeatedly (high total waiting), but no job waits long before its first slice (low response).
Real schedulers and multicore
Linux’s CFS (Completely Fair Scheduler, replaced by EEVDF in 6.6) tracks vruntime, the CPU time a task has received weighted by its priority. It always picks the task with the smallest vruntime, which approximates giving every task an equal share of a virtual CPU. The run queue is a red-black tree keyed by vruntime, so picking the next task is \(O(\log n)\).
Multicore adds two problems:
- Load balancing: move runnable threads from busy cores to idle ones, without destroying cache locality.
- Affinity: keep a thread on the same core when possible; migrating it loses warm caches and TLB entries.
Real-time policies (SCHED_FIFO, SCHED_RR) sit above the fair scheduler and are
used for audio, robotics, and anything with a deadline.
ASolution
It needs the task with the minimum vruntime, plus efficient insertion and removal. A balanced tree gives all three in \(O(\log n)\).
Bugs and edge cases
- Ignoring arrival times. A job cannot start before it arrives; the Gantt chart must show idle time when the queue is empty.
- Forgetting preemption. SRTF and RR interrupt the running job; FCFS, SJF, and non-preemptive priority do not.
- Quantum smaller than the switch cost. Throughput collapses; the CPU spends its time switching.
- Starvation. SJF, SRTF, and priority need aging or a boost.
- Confusing waiting and turnaround. Waiting excludes the burst; turnaround includes it.
- Assuming fairness means equal time. Fairness can mean equal share, priority share, or deadline compliance; they are different metrics.
50 µs per context switch. What fraction of CPU is lost?
ASolution
\(50/(1000+50) \approx 4.8\%\). Shorter quanta make it worse: at 100 µs quantum, a third of the CPU disappears into switching.
Next: Concurrency and Synchronization (OS Core #4) — races, locks, and the four conditions for deadlock.