CPU scheduling: FCFS, SJF, priority, round robin
The scheduler decides which process runs next: first come first served, shortest job first, priority or round robin. Compare them on a Gantt chart.
The idea
You hold one item. The cart ahead holds fifty, so you wait ten minutes for a one-minute job.
A CPU has the same problem. Many processes are ready, one core runs them, and the order decides how long each one waits.
Intuition
First come, first served (FCFS) runs P1, P2, P3 in arrival order. Short P3 waits 12 behind long P1.
Waiting time is the time a process is ready but not running. Here the waits are 0, 8 and 12, an average of 6.67.
Shortest job first (SJF) runs P3, then P2, then P1. The average wait drops from 6.67 to 2.67.
The waits are 0, 2 and 6. Every process waits for the bursts that run before it, so putting short bursts first keeps the sum small.
Priority scheduling runs the most important process first. Here P2 has priority 1, so it goes before the others.
Priority ignores burst length. It suits systems where some work must react fast, such as input handling.
Complexity
Each pick scans the ready list, so n processes cost O(n²) in total. A heap keyed by the policy cuts this to O(n log n).
Round robin needs no search: the queue front is the next process, O(1) per slice. The number of slices is the sum of burst / quantum, rounded up.
Pitfalls
Under SJF or priority, a long job can wait forever while shorter jobs keep arriving. This is starvation.
SJF is optimal for average waiting time, but it gives no promise to any single process. Real schedulers add aging to bound the wait.
A tiny quantum wastes time on switches between processes. A huge quantum turns round robin into FCFS.
A context switch saves one process's registers and loads another's. Quanta of a few milliseconds keep switches rare and the system responsive.
Variations
Shortest remaining time first (SRTF) is preemptive SJF. A new arrival with less work left takes the CPU at once.
Aging raises a waiting process's priority over time, so it cannot starve. Real systems use many queues with this idea.
Code
Pseudocode
time ← 0, ready ← empty
while some process is unfinished
move every process with arrival ≤ time into ready
if ready is empty: time ← next arrival; continue
p ← pick from ready (FCFS: earliest arrival, SJF: shortest burst,
priority: lowest number, RR: front of the queue)
run ← left[p], or min(quantum, left[p]) for RR
time ← time + run; left[p] ← left[p] − run
if left[p] = 0: wait[p] ← time − arrival[p] − burst[p]
else: move new arrivals in, then put p at the back of ready
return wait
Python
def schedule(procs, policy, quantum):
left = [p["burst"] for p in procs]
wait = [0] * len(procs)
todo = sorted(procs, key=lambda p: p["arrival"])
ready, time, finished = [], 0, 0
while finished < len(procs):
while todo and todo[0]["arrival"] <= time:
ready.append(todo.pop(0))
if not ready:
time = todo[0]["arrival"]
continue
p = pick(ready, policy)
run = min(quantum, left[p["id"]]) if policy == "rr" else left[p["id"]]
time += run
left[p["id"]] -= run
while todo and todo[0]["arrival"] <= time:
ready.append(todo.pop(0))
if left[p["id"]] == 0:
wait[p["id"]] = time - p["arrival"] - p["burst"]
finished += 1
else:
ready.append(p)
return wait
def pick(ready, policy):
if policy == "rr":
return ready.pop(0)
key = {"sjf": "burst", "priority": "priority"}.get(policy, "arrival")
best = min(range(len(ready)), key=lambda k: ready[k][key])
return ready.pop(best)
JavaScript
function schedule(procs, policy, quantum) {
const left = procs.map((p) => p.burst), wait = procs.map(() => 0);
const todo = procs.slice().sort((a, b) => a.arrival - b.arrival), ready = [];
let time = 0, finished = 0;
while (finished < procs.length) {
while (todo.length && todo[0].arrival <= time) ready.push(todo.shift());
if (ready.length === 0) { time = todo[0].arrival; continue; }
const p = pick(ready, policy);
const run = policy === "rr" ? Math.min(quantum, left[p.id]) : left[p.id];
time += run; left[p.id] -= run;
while (todo.length && todo[0].arrival <= time) ready.push(todo.shift());
if (left[p.id] === 0) { wait[p.id] = time - p.arrival - p.burst; finished++; }
else ready.push(p);
}
return wait;
}
function pick(ready, policy) {
if (policy === "rr") return ready.shift();
const key = (p) => (policy === "sjf" ? p.burst : policy === "priority" ? p.priority : p.arrival);
let best = 0;
for (let k = 1; k < ready.length; k++) if (key(ready[k]) < key(ready[best])) best = k;
return ready.splice(best, 1)[0];
}
Practice problems (6)
Compute waiting time Warm-up
Non-preemptive SJF ran three processes and produced the Gantt chart below.
| Process | Arrival | Burst | |---|---|---| | P1 | 0 | 7 | | P2 | 2 | 4 | | P3 | 4 | 1 |
What is the average waiting time?
FCFS waiting times Warm-up
Process i arrives at time arrival[i] and needs the CPU for burst[i] time units. First come, first served runs processes in order of arrival; ties go to the lower index. A process runs to completion once it starts, and the CPU idles when nobody has arrived.
Return an array whose i-th value is the waiting time of process i: the time between its arrival and its start.
Best policy for a goal Standard
A shared server runs many interactive terminal sessions. Each session sends short commands, and some users also start long jobs. The goal: every user sees a response within a bounded time, and no job waits forever. Burst lengths are not known in advance.
Which policy fits this goal best?
Build the round-robin schedule Standard
Round robin with quantum 2 runs P1 (arrival 0, burst 5), P2 (arrival 1, burst 3) and P3 (arrival 2, burst 4). A process that arrives while another runs joins the queue before the preempted process goes to the back. Build the schedule, then read the waiting time off the chart.
Round-robin finish times Standard
Process i arrives at arrival[i] and needs burst[i] units of CPU. Round robin keeps a FIFO queue of ready processes. The front process runs for min(quantum, time left). If it is not done, it goes to the back of the queue, after any process that arrived up to and including that moment. Processes arriving at the same time join in index order. The CPU idles when the queue is empty.
Return an array whose i-th value is the time process i finishes.
Simulate SJF in code Challenge
Process i arrives at arrival[i] and needs burst[i] units of CPU. Non-preemptive shortest job first works like this: whenever the CPU is free, it starts the ready process with the shortest burst and runs it to completion. A process is ready once its arrival time has passed. If nobody is ready, the CPU idles until the next arrival.
Return the total waiting time over all processes (start − arrival, summed).
Next on the path: Finite automata: DFA and NFA