Lesson 5 · Processes, threads, and CPU scheduling

CPU Scheduling Algorithms

Many processes are ready to run and the CPU can run one at a time. A scheduling algorithm is the rule that picks the next one. Each rule is best at one measure, such as waiting time or response time, and pays for it somewhere else.

CPU Scheduling Algorithms concept diagramA visual explanation of the layout and operations shown in this lesson.P1=6 · P2=2 · P3=4, all arrive at t=0 · quantum 2024681012FCFSP1P2P3waits 0, 6, 8 → average 4.67 · P2 waits 6 for a 2-unit jobSJFP2P3P1waits 0, 2, 6 → average 2.67 · provably the minimumRound robinP1P2P3P1P3P1first response 0, 2, 4 → average 2.00 · 5 context switchesSJF minimises waiting; round robin minimises response — the same jobs, three different answers
1

Scheduling Criteria

In an operating system, CPU scheduling decides which ready process runs next on a free CPU. The short-term scheduler makes this choice many times a second; the other kinds of scheduler are compared in types of schedulers. Before comparing rules, fix what "better" means, because no rule wins on every measure.

The two measures exams ask for most are turnaround time and waiting time. Turnaround is completion time minus arrival time: how long the job took from start to finish. Waiting time is turnaround minus the CPU burst: the time spent sitting in the ready queue. Response time is the time until a job first gets the CPU, and it is what a person at a keyboard feels.

On the system side, throughput is jobs finished per unit of time and CPU utilisation is the share of time the CPU does useful work. Shortest-first rules cut waiting but can starve long jobs; frequent switching improves response but costs throughput.

  • Turnaround = completion − arrival
  • Waiting = turnaround − burst
  • Response = first run − arrival
2

Preemptive and Non-Preemptive Scheduling

Preemptive and non preemptive scheduling differ in when the scheduler may act. Non-preemptive scheduling lets the running process keep the CPU until it finishes or blocks for I/O. Preemptive scheduling can take the CPU away in the middle of a burst, either when a timer runs out or when a more important process arrives.

Preemption is what keeps a modern system responsive: a program stuck in a loop cannot freeze the machine, because the timer interrupt always hands control back to the kernel. The price is more context switches, and shared data must be protected because a process can be stopped at any point.

  • Non-preemptive: FCFS, SJF, non-preemptive priority
  • Preemptive: SRTF, round robin, preemptive priority, multilevel feedback queue
3

The Main Process Scheduling Algorithms

These are the process scheduling algorithms every OS course covers. Each has its own lesson with worked examples; here is what each one does and where it breaks.

FCFS runs processes in arrival order, each to completion. It is fair and needs only a queue, but one long job at the front makes every short job wait: the convoy effect.

SJF runs the shortest burst first, which gives the lowest possible average waiting time for a set of jobs. The OS cannot know burst lengths in advance, so it predicts them from past bursts. Its preemptive form, SRTF, switches whenever a new job has less remaining time. Both can starve long jobs.

Round robin gives each process a fixed time quantum, then preempts it and sends it to the back of the queue. A quantum longer than the bursts turns it into FCFS; a very short one wastes the CPU on switching.

Priority scheduling runs the highest-priority ready process. Low-priority work can wait forever unless the OS uses aging, raising a process's priority the longer it waits.

Multilevel feedback queues use several queues with different quanta and move processes between them based on behaviour, so interactive work stays at the top without being labelled in advance.

  • Starvation risk: SJF, SRTF and priority (without aging)
  • No starvation: FCFS and round robin
Key reference

Terms, operations, and practical uses

Metrics

  • TurnaroundArrival to completion.
  • WaitingTurnaround minus the actual CPU burst.
  • ResponseArrival to first execution — what a user feels.
  • ThroughputJobs completed per unit time.

Non-preemptive

  • FCFSArrival order; suffers the convoy effect.
  • SJFOptimal average waiting time, needs unknowable burst lengths.
  • Convoy effectOne long job at the front delays every short job behind it.

Preemptive

  • SRTFPreemptive SJF; better still, and starves long jobs harder.
  • Round robinFixed quantum, then the job goes to the back of the queue; too long becomes FCFS, too short wastes time switching.
  • Priority schedulingRuns the highest-ranked ready process; starves the bottom without aging.
  • Multilevel queueSeparate queues by process class, each with its own policy.
  • QuantumToo long becomes FCFS, too short burns CPU on switching.
  • AgingRaises a waiting process's priority so it cannot starve.
Implementation

FCFS, SJF, round robin and priority on one job set

from collections import deque

# Four scheduling policies on the same three jobs. Total work is 12 units
# either way -- the only thing a scheduler controls is the order.
JOBS = [('P1', 6), ('P2', 2), ('P3', 4)]
PRIORITY = {'P1': 1, 'P3': 2, 'P2': 3}        # lower number = higher priority

def run(sequence):
    """Return (first_cpu, completion) times for a list of (name, slice)."""
    first, done, t = {}, {}, 0
    for name, length in sequence:
        first.setdefault(name, t)             # response = first time on CPU
        t += length
        done[name] = t
    return first, done

def averages(sequence):
    burst = dict(JOBS)
    first, done = run(sequence)
    wait = {n: done[n] - burst[n] for n in done}   # wait = turnaround - burst
    n = len(burst)
    return sum(wait.values()) / n, sum(first.values()) / n

fcfs = list(JOBS)                                   # arrival order
sjf = sorted(JOBS, key=lambda j: j[1])              # shortest burst first
prio = sorted(JOBS, key=lambda j: PRIORITY[j[0]])   # highest priority first

rr, ready = [], deque(JOBS)                         # preemptive, quantum 2
while ready:
    name, left = ready.popleft()
    slice_ = min(2, left)
    rr.append((name, slice_))
    if left - slice_:
        ready.append((name, left - slice_))         # unfinished goes to the back

fw, _ = averages(fcfs)
sw, _ = averages(sjf)
_, rr_resp = averages(rr)
pw, _ = averages(prio)
print(f"FCFS wait {fw:.2f} | SJF wait {sw:.2f} "
      f"| RR response {rr_resp:.2f} | Priority wait {pw:.2f}")
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <deque>
#include <algorithm>
#include <iomanip>
using namespace std;

// Four scheduling policies on the same three jobs. Total work is 12 units
// either way -- the only thing a scheduler controls is the order.
struct Job { string name; int burst; };

// Returns {average waiting time, average response time} for a run sequence.
pair<double, double> averages(const vector<pair<string,int>>& seq,
                              const map<string,int>& burst) {
    map<string,int> first, done;
    int t = 0;
    for (auto& s : seq) {
        if (!first.count(s.first)) first[s.first] = t;  // first time on CPU
        t += s.second;
        done[s.first] = t;
    }
    double w = 0, r = 0;
    for (auto& b : burst) {
        w += done[b.first] - b.second;                  // turnaround - burst
        r += first[b.first];
    }
    return {w / burst.size(), r / burst.size()};
}

int main() {
    vector<Job> jobs{{"P1", 6}, {"P2", 2}, {"P3", 4}};
    map<string,int> burst, priority{{"P1",1},{"P3",2},{"P2",3}};
    for (auto& j : jobs) burst[j.name] = j.burst;

    vector<pair<string,int>> fcfs, sjf, prio, rr;
    for (auto& j : jobs) fcfs.push_back({j.name, j.burst});   // arrival order

    sjf = fcfs;
    sort(sjf.begin(), sjf.end(), [](auto& a, auto& b){ return a.second < b.second; });

    prio = fcfs;
    sort(prio.begin(), prio.end(), [&](auto& a, auto& b){
        return priority[a.first] < priority[b.first];
        });

    deque<pair<string,int>> ready(fcfs.begin(), fcfs.end());  // quantum 2
    while (!ready.empty()) {
        auto [name, left] = ready.front();
        ready.pop_front();
        int slice = min(2, left);
        rr.push_back({name, slice});
        if (left - slice) ready.push_back({name, left - slice});
    }

    cout << fixed << setprecision(2)
         << "FCFS wait " << averages(fcfs, burst).first
         << " | SJF wait " << averages(sjf, burst).first
         << " | RR response " << averages(rr, burst).second
         << " | Priority wait " << averages(prio, burst).first << "\n";
}
import java.util.*;

class Main {
    // Four scheduling policies on the same three jobs. Total work is 12 units
    // either way -- the only thing a scheduler controls is the order.
    record Slice(String name, int len) {}

    // Returns {average waiting time, average response time} for a run sequence.
    static double[] averages(List<Slice> seq, Map<String,Integer> burst) {
        Map<String,Integer> first = new HashMap<>(), done = new HashMap<>();
        int t = 0;
        for (Slice s : seq) {
            first.putIfAbsent(s.name(), t);              // first time on CPU
            t += s.len();
            done.put(s.name(), t);
        }
        double w = 0, r = 0;
        for (var e : burst.entrySet()) {
            w += done.get(e.getKey()) - e.getValue();    // turnaround - burst
            r += first.get(e.getKey());
        }
        return new double[]{ w / burst.size(), r / burst.size() };
    }

    public static void main(String[] args) {
        List<Slice> fcfs = List.of(new Slice("P1", 6), new Slice("P2", 2),
                                   new Slice("P3", 4));  // arrival order
        Map<String,Integer> burst = new LinkedHashMap<>();
        for (Slice s : fcfs) burst.put(s.name(), s.len());
        Map<String,Integer> priority = Map.of("P1", 1, "P3", 2, "P2", 3);

        List<Slice> sjf = new ArrayList<>(fcfs);
        sjf.sort(Comparator.comparingInt(Slice::len));

        List<Slice> prio = new ArrayList<>(fcfs);
        prio.sort(Comparator.comparingInt(s -> priority.get(s.name())));

        List<Slice> rr = new ArrayList<>();               // quantum 2
        Deque<Slice> ready = new ArrayDeque<>(fcfs);
        while (!ready.isEmpty()) {
            Slice cur = ready.pollFirst();
            int slice = Math.min(2, cur.len());
            rr.add(new Slice(cur.name(), slice));
            if (cur.len() - slice > 0)
                ready.addLast(new Slice(cur.name(), cur.len() - slice));
        }

        System.out.printf("FCFS wait %.2f | SJF wait %.2f "
            + "| RR response %.2f | Priority wait %.2f%n",
            averages(fcfs, burst)[0], averages(sjf, burst)[0],
            averages(rr, burst)[1], averages(prio, burst)[0]);
    }
}
Watch it run

Step through it

Running on P1 = 6, P2 = 2, P3 = 4 at t = 0; quantum 2; priority P1 > P3 > P2

P1 = 6, P2 = 2, P3 = 4, all arrive at t = 0CPU0123456789101112CPU burst neededP16P22P34same work, different orders: waiting time is what changesinputtotal work12jobs3arrivalall at 0
Step 1

Three jobs, one CPU

P1 needs 6 units of CPU time, P2 needs 2 and P3 needs 4. All three are ready at time 0, so the only thing a scheduler can change is the order. Whatever it picks, the CPU finishes all the work at time 12.

Output
1 / 10
4

One Job Set, Four Answers

Take P1 = 6, P2 = 2 and P3 = 4 units, all arriving at time 0, a quantum of 2 for round robin, and priorities P1 > P3 > P2. The work is 12 units whatever the order, yet the averages differ a lot.

SJF has the lowest average waiting time (2.67). Round robin has the same waiting as FCFS (4.67) but halves average response to 2.00, because every job starts by time 4. Priority puts the shortest job last, so P2 waits 10 units. The tracer draws each Gantt chart and the failure cases.

P1 = 6, P2 = 2, P3 = 4 at t = 0; RR quantum 2; priority P1 > P3 > P2
AlgorithmOrderAvg waitingAvg turnaroundAvg response
FCFSP1 P2 P34.678.674.67
SJFP2 P3 P12.676.672.67
Round robinP1 P2 P3 P1 P3 P14.678.672.00
PriorityP1 P3 P25.339.335.33
  • Waiting for P2 under FCFS: it starts at 6, so it waits 6 units for 2 units of work
  • Round robin pays for its response with 5 context switches instead of 2
5

Choosing an Algorithm

Batch systems, where nobody is waiting, favour FCFS or SJF for throughput. Interactive systems need preemption and short quanta for response. Real-time systems schedule by deadline, as in earliest deadline first.

Real kernels mix these ideas. Windows and classic Unix use multilevel feedback queues with priorities. Linux used the Completely Fair Scheduler, which always runs the task that has had the least weighted CPU time; since kernel 6.6 it uses EEVDF, which adds a deadline to each task's turn. With several CPUs, the kernel also decides which core runs each task: see multiprocessor scheduling.

How the main algorithms compare
AlgorithmPreemptiveBest atStarvationMain weakness
FCFSNoSimplicityNoConvoy effect
SJFNoAverage waiting timeYesNeeds burst lengths in advance
SRTFYesAverage waiting timeYesMore switches
Round robinYesResponse timeNoQuantum choice
PriorityEitherImportant work firstYes, without agingPriority inversion
Multilevel feedbackYesMixed workloadsRare, with priority boostsMany settings to tune
  • No algorithm wins every measure; pick by what the users are waiting for