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.
One Number Decides Who Runs
- Priority – an integer attached to each process; in this lesson a lower number means higher priority (0 or 1 is most important).
- Rule – the CPU goes to the ready process with the highest priority.
- Ties – broken by arrival order, i.e. FCFS among equal priorities.
- Variants – preemptive and non-preemptive.
- 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
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.
| Preemptive | Non-preemptive | |
|---|---|---|
| Decision points | Every arrival and every completion | Only when the running process finishes or blocks |
| Higher-priority arrival | Takes the CPU immediately | Waits at the head of the ready queue |
| Response for urgent work | Best possible | Delayed by the current burst |
| Context switches | More | Fewer |
| Typical use | General-purpose and real-time OS kernels | Simple 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
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
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.
Related lessons
- SJF schedulingThe special case where priority = burst length.
- Round robin schedulingEqual turns instead of ranked ones.
- Multilevel feedback queuePriorities that change with observed behaviour.
- Real-time operating systemsPriority inversion and the Mars Pathfinder bug.
- Lottery schedulingProportional shares by ticket instead of absolute priority.
- FCFS schedulingThe arrival-order rule used to break ties.
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);
}
}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)
A Solved Example With Every Arrival at t = 0
- Given – burst (priority): P1 = 10 (3), P2 = 1 (1), P3 = 2 (4), P4 = 1 (5), P5 = 5 (2); all arrive at t = 0.
- Order – sort by priority: P2, P5, P1, P3, P4.
- Gantt chart – P2 0–1, P5 1–6, P1 6–16, P3 16–18, P4 18–19.
- 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.
| Process | Burst | Priority | Start | Completion | Turnaround | Waiting |
|---|---|---|---|---|---|---|
| P1 | 10 | 3 | 6 | 16 | 16 | 6 |
| P2 | 1 | 1 | 0 | 1 | 1 | 0 |
| P3 | 2 | 4 | 16 | 18 | 18 | 16 |
| P4 | 1 | 5 | 18 | 19 | 19 | 18 |
| P5 | 5 | 2 | 1 | 6 | 6 | 1 |
| Average | 12 | 8.2 |
- Turnaround = completion − arrival; waiting = turnaround − burst
- The tracer above repeats the exercise with staggered arrivals, where preemption matters
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
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
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