Lesson 9 · Processes, threads, and CPU scheduling

Priority Scheduling

Give every process a priority and always run the most important ready one. Simple and powerful — until a low-priority process waits forever, which is why aging exists.

Priority Scheduling concept diagramThe same two processes scheduled twice. Non-preemptive: the low-priority job L keeps the CPU and the high-priority job H waits. Preemptive: H takes the CPU the moment it arrives and L resumes afterwards.L: low priority (3), burst 6, arrives t = 0H: high priority (1), burst 2, arrives t = 2non-preemptiveLH02468H waits 4 — it arrived but L keeps the CPUpreemptiveLHL02468H waits 0 — L is interrupted and resumes at 4H arrivesboth run the higher priority first — they differ only in whether an arrival can interrupt
1

One Number Decides Who Runs

  1. Priority – an integer attached to each process; in this lesson a lower number means higher priority (0 or 1 is most important).
  2. Rule – the CPU goes to the ready process with the highest priority.
  3. Ties – broken by arrival order, i.e. FCFS among equal priorities.
  4. Variants – preemptive and non-preemptive.
  5. Main risk – starvation of low-priority processes, fixed by aging.

Priority scheduling is a CPU scheduling algorithm that assigns every process a priority and always dispatches the most important ready process. It generalises the other classic algorithms: SJF is the case where the priority is the predicted next burst length, and FCFS the case where every process has the same priority.

Whether a small number means high or low priority is only a convention. Linux uses lower numbers for higher priority (nice −20 is the most favoured); some textbooks and systems use the opposite. An exam answer should always state the convention it uses.

  • Only ready processes are ranked; a blocked process waits for its event, whatever its priority
  • If a question does not say which way the numbers run, state your assumption first
2

Preemptive vs Non-Preemptive Priority Scheduling

The two versions choose the same process whenever the CPU is free. They differ in what happens when a higher-priority process arrives while another is running. Preemptive priority scheduling interrupts the running process at once and puts it back in the ready queue; non-preemptive priority scheduling lets the running process finish its burst, and the newcomer goes to the head of the ready queue.

The hero diagram shows the difference on two processes: the high-priority job waits 4 units under non-preemptive scheduling and 0 under preemptive. Preemption gives better response to urgent work, at the cost of extra context switches and the need to protect shared data from interruption.

The two forms compared
PreemptiveNon-preemptive
Decision pointsEvery arrival and every completionOnly when the running process finishes or blocks
Higher-priority arrivalTakes the CPU immediatelyWaits at the head of the ready queue
Response for urgent workBest possibleDelayed by the current burst
Context switchesMoreFewer
Typical useGeneral-purpose and real-time OS kernelsSimple batch systems
  • An arrival with the same priority as the running process never preempts it; it queues behind
  • Real-time kernels are preemptive priority schedulers
3

How Priorities Are Assigned

Internal priorities are computed by the OS from measurable properties: memory needs, number of open files, the ratio of I/O time to CPU time, time limits. External priorities are set from outside: the importance of the user or job, a price paid for service, or an administrator's decision such as Unix nice.

Priorities can also be static — fixed for the life of the process — or dynamic, changing as the process runs. Dynamic priority is what makes aging possible, and it is how general-purpose schedulers favour interactive programs: a process that often blocks for I/O gets its priority raised.

  • Unix nice values run from −20 (most favoured) to 19 (least)
  • Windows has 32 levels; 16 to 31 are the real-time range
  • Dynamic priority is the basis of aging and of feedback queues
Key reference

Terms, operations, and practical uses

Terms to know

  • StarvationA ready process that is never scheduled because others always outrank it.
  • AgingRaising a process's priority the longer it waits.
  • Priority inversionA high-priority task blocked by a lower one through a shared lock.
  • Priority inheritanceA lock holder temporarily runs at the highest priority waiting on its lock.
Implementation

Code in Python, C++ and Java

import heapq


def preemptive_priority(processes):
    # processes: (name, arrival, burst, priority); a lower number runs first.
    procs = sorted(processes, key=lambda p: p[1])
    remaining = {name: burst for name, _, burst, _ in procs}
    ready, gantt, finish = [], [], {}
    clock, i = 0, 0
    while len(finish) < len(procs):
        while i < len(procs) and procs[i][1] <= clock:
            name, arrival, _, priority = procs[i]
            # Ties on priority go to the earlier arrival.
            heapq.heappush(ready, (priority, arrival, name))
            i += 1
        if not ready:
            clock = procs[i][1]
            continue
        priority, arrival, name = ready[0]
        # Run until this job ends or the next arrival might preempt it.
        next_arrival = procs[i][1] if i < len(procs) else float("inf")
        run = min(remaining[name], next_arrival - clock)
        if gantt and gantt[-1][0] == name:
            gantt[-1][2] += run
        else:
            gantt.append([name, clock, clock + run])
        clock += run
        remaining[name] -= run
        if remaining[name] == 0:
            heapq.heappop(ready)
            finish[name] = clock
    return gantt, finish


procs = [("P1", 0, 5, 3), ("P2", 1, 3, 1), ("P3", 2, 2, 4), ("P4", 3, 4, 2), ("P5", 4, 1, 5)]
gantt, finish = preemptive_priority(procs)
print("Gantt:", " ".join(f"{n}@{s}" for n, s, _ in gantt), f"end@{gantt[-1][2]}")

total_tat = total_wt = 0
for name, arrival, burst, _ in procs:
    tat = finish[name] - arrival
    total_tat += tat
    total_wt += tat - burst
    print(f"{name}: completion {finish[name]:>2}  turnaround {tat:>2}  waiting {tat - burst:>2}")
print(f"average turnaround {total_tat / len(procs):.2f}, average waiting {total_wt / len(procs):.2f}")
#include <algorithm>
#include <climits>
#include <cstdio>
#include <queue>
#include <string>
#include <tuple>
#include <vector>
using namespace std;

struct Process {
    string name;
    int arrival, burst, priority;  // a lower priority number runs first
    int remaining = 0, finish = 0;
};

int main() {
    vector<Process> procs = {{"P1", 0, 5, 3}, {"P2", 1, 3, 1}, {"P3", 2, 2, 4},
                             {"P4", 3, 4, 2}, {"P5", 4, 1, 5}};
    for (Process& p : procs) p.remaining = p.burst;

    // (priority, arrival, index): ties on priority go to the earlier arrival.
    using Entry = tuple<int, int, int>;
    priority_queue<Entry, vector<Entry>, greater<Entry>> ready;
    size_t next = 0;
    int clock = 0, done = 0, lastRun = -1;

    printf("Gantt:");
    while (done < (int)procs.size()) {
        while (next < procs.size() && procs[next].arrival <= clock) {
            ready.push({procs[next].priority, procs[next].arrival, (int)next});
            next++;
        }
        if (ready.empty()) {
            clock = procs[next].arrival;
            continue;
        }
        int i = get<2>(ready.top());
        // Run until this job ends or the next arrival might preempt it.
        int nextArrival = next < procs.size() ? procs[next].arrival : INT_MAX;
        int run = min(procs[i].remaining, nextArrival - clock);
        if (i != lastRun) printf(" %s@%d", procs[i].name.c_str(), clock);
        lastRun = i;
        clock += run;
        procs[i].remaining -= run;
        if (procs[i].remaining == 0) {
            ready.pop();
            procs[i].finish = clock;
            done++;
        }
    }
    printf(" end@%d\n", clock);

    double totalTat = 0, totalWt = 0;
    for (const Process& p : procs) {
        int tat = p.finish - p.arrival;
        totalTat += tat;
        totalWt += tat - p.burst;
        printf("%s: completion %2d  turnaround %2d  waiting %2d\n", p.name.c_str(), p.finish, tat, tat - p.burst);
    }
    printf("average turnaround %.2f, average waiting %.2f\n", totalTat / procs.size(), totalWt / procs.size());
    return 0;
}
import java.util.Comparator;
import java.util.PriorityQueue;

public class Main {
    static class Process {
        final String name;
        final int arrival, burst, priority; // a lower priority number runs first
        int remaining, finish;

        Process(String name, int arrival, int burst, int priority) {
            this.name = name;
            this.arrival = arrival;
            this.burst = burst;
            this.priority = priority;
            this.remaining = burst;
        }
    }

    public static void main(String[] args) {
        Process[] procs = {
            new Process("P1", 0, 5, 3), new Process("P2", 1, 3, 1), new Process("P3", 2, 2, 4),
            new Process("P4", 3, 4, 2), new Process("P5", 4, 1, 5)
        };

        // Ties on priority go to the earlier arrival.
        PriorityQueue<Process> ready = new PriorityQueue<>(
                Comparator.comparingInt((Process p) -> p.priority).thenComparingInt(p -> p.arrival));
        int next = 0, clock = 0, done = 0;
        Process lastRun = null;
        StringBuilder gantt = new StringBuilder("Gantt:");

        while (done < procs.length) {
            while (next < procs.length && procs[next].arrival <= clock) ready.add(procs[next++]);
            if (ready.isEmpty()) {
                clock = procs[next].arrival;
                continue;
            }
            Process p = ready.peek();
            // Run until this job ends or the next arrival might preempt it.
            int nextArrival = next < procs.length ? procs[next].arrival : Integer.MAX_VALUE;
            int run = Math.min(p.remaining, nextArrival - clock);
            if (p != lastRun) gantt.append(" ").append(p.name).append("@").append(clock);
            lastRun = p;
            clock += run;
            p.remaining -= run;
            if (p.remaining == 0) {
                ready.poll();
                p.finish = clock;
                done++;
            }
        }
        System.out.println(gantt + " end@" + clock);

        double totalTat = 0, totalWt = 0;
        for (Process p : procs) {
            int tat = p.finish - p.arrival;
            totalTat += tat;
            totalWt += tat - p.burst;
            System.out.printf("%s: completion %2d  turnaround %2d  waiting %2d%n", p.name, p.finish, tat, tat - p.burst);
        }
        System.out.printf("average turnaround %.2f, average waiting %.2f%n",
                totalTat / procs.length, totalWt / procs.length);
    }
}
Watch it run

Step through it

Running on (arrival, burst, priority): P1 (0,5,3) P2 (1,3,1) P3 (2,2,4) P4 (3,4,2) P5 (4,1,5)

not arrivedreadydonepr 1 highP2 @1pr 2P4 @3pr 3P1 @0pr 4P3 @2pr 5 lowP5 @4before t = 0CPU: idleGantt chart0lower number = higher priority; ties → earlier arrival
Step 1

Five processes, each with a priority

The scheduler always runs the ready process with the highest priority — here the smallest number. This version is preemptive: a newly arrived process with higher priority takes the CPU at once.

Output
1 / 12
4

A Solved Example With Every Arrival at t = 0

  1. Given – burst (priority): P1 = 10 (3), P2 = 1 (1), P3 = 2 (4), P4 = 1 (5), P5 = 5 (2); all arrive at t = 0.
  2. Order – sort by priority: P2, P5, P1, P3, P4.
  3. Gantt chart – P2 0–1, P5 1–6, P1 6–16, P3 16–18, P4 18–19.
  4. Averages – waiting 41 / 5 = 8.2 ms; turnaround 60 / 5 = 12 ms.

When every process arrives at t = 0, preemptive and non-preemptive give the same schedule, because no arrival ever happens mid-burst. Sort by priority, lay the bursts end to end, and each process's waiting time is simply its start time.

The result shows the algorithm's character. P4 needs only 1 ms, but with the lowest priority it waits 18 ms — longer than anyone else. Priority scheduling optimises for importance, not for average waiting time; SJF on the same bursts would average 3.2 ms.

Non-preemptive, all arrivals at 0
ProcessBurstPriorityStartCompletionTurnaroundWaiting
P1103616166
P2110110
P32416181816
P41518191918
P5521661
Average128.2
non-preemptive priority, all arrive at t = 0 (1 = highest)P2pr 1P5pr 2P1pr 3P3pr 4P4pr 5016161819waiting = start time: P2 0, P5 1, P1 6, P3 16, P4 18 → average 41 / 5 = 8.2
  • Turnaround = completion − arrival; waiting = turnaround − burst
  • The tracer above repeats the exercise with staggered arrivals, where preemption matters
5

Starvation and Aging

Starvation (indefinite blocking) is the main weakness of ranking by priority. On a busy system, a steady stream of higher-priority processes can keep a low-priority process in the ready queue forever. It is ready to run, never blocked on anything, and still never runs.

Aging is the standard solution: gradually increase the priority of processes that have waited a long time. For example, raise a waiting process by one level every 15 minutes; a process that starts at priority 127 then reaches priority 0 in under 32 hours and must eventually run. The tracer shows a faster version, one level every 4 time units.

Aging bounds the waiting time of every process without giving up priority ordering in the short term, which is why general-purpose schedulers use some form of it — often as the priority boost in a multilevel feedback queue.

  • Starvation is not deadlock: nothing blocks the process, it is simply always outranked
  • Once an aged process has run, its priority drops back, or every process would end at the top
6

Priority Inversion and Priority Inheritance

Priority inversion happens when a high-priority task H waits for a lock held by a low-priority task L, and a medium-priority task M — which needs no lock at all — preempts L. H is now effectively waiting for M, a task less important than itself. The inversion is unbounded if more medium tasks keep arriving.

The fix is priority inheritance: while L holds a lock that H needs, L temporarily runs at H's priority, so M cannot preempt it. L releases the lock quickly and drops back to its own priority. This exact bug reset the Mars Pathfinder lander in 1997 until priority inheritance was switched on remotely; the real-time OS lesson covers the incident.

  • Inversion: H waits on L's lock while M runs
  • Inheritance: L borrows H's priority while holding the lock
  • Mars Pathfinder, 1997: fixed by enabling inheritance
  • Real-time systems must bound inversion, not just avoid it
7

Strengths and Limits

A fixed ranking is the easiest way to say that some work matters more than other work: kernel threads before user programs, interactive programs before batch jobs, a flight controller before a log writer. Its costs come from the same ranking: low-priority work can starve, shared locks can invert the order, and average waiting time is not minimised, since the most important job is not always the shortest.

  • Strength: important work runs first, and the preemptive form responds to it at once
  • Strength: SJF and FCFS are special cases, so one mechanism covers many policies
  • Limit: starvation, unless aging is added
  • Limit: priority inversion with shared locks, unless inheritance is used