Notes
All notes

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:

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.

QQuestionA job arrives at 3, runs for 5, and finishes at 12. What are its

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.

QQuestionWhy is a preemptive scheduler required for interactive systems?
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.

QQuestionWhy does FCFS give poor average waiting time?
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.

QQuestionWhy is SJF optimal for average waiting time?
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:

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.

QQuestionWhat extra information does SRTF need that SJF does not?
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.

QQuestionHow does aging prevent starvation?
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:

QQuestionA system has 100 runnable processes and a 10 ms quantum. How long

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:

\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.

QQuestionWhy does MLFQ need a periodic boost?
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.

QQuestionWhy does the RR row have the worst waiting time but the best

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:

Real-time policies (SCHED_FIFO, SCHED_RR) sit above the fair scheduler and are used for audio, robotics, and anything with a deadline.

QQuestionWhy does CFS use a red-black tree instead of a queue?
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

QQuestionA scheduler gives every job a 1 ms quantum and the machine takes

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.