Process Scheduling Algorithms
A comprehensive guide to CPU scheduling algorithms including FCFS, SJF, Round Robin, Priority scheduling, and multi-level feedback queues.
A comprehensive guide to CPU scheduling algorithms including FCFS, SJF, Round Robin, Priority scheduling, and multi-level feedback queues.
Process Scheduling Algorithms
Imagine you’re an air traffic controller managing a runway. Planes arrive at different times, need different amounts of runway time, and may have different urgency. You want to keep the runway busy without leaving one plane waiting forever.
That is the kind of tradeoff a scheduling policy models. The examples below use simplified, single-CPU workloads so you can see how the rules affect wait and response time.
Introduction
CPU scheduling algorithms decide which runnable process to run next on each CPU core. The scheduler makes this decision based on various factors: burst time, priority, waiting time, and the scheduling policy.
These algorithms are teaching models, not a list of policies that every operating system implements directly. Current Linux documentation describes its fair scheduling code as transitioning from CFS toward EEVDF beginning with Linux 6.6. Linux also has a separate SCHED_RR real-time policy; the default SCHED_OTHER policy is not fixed round robin. See the Linux 7.0 EEVDF documentation and sched(7). The implementation you observe depends on kernel version, scheduling policy, configuration, and resource controls.
When to Use
- System tuning — Choosing the right scheduler improves responsiveness
- Real-time applications — Guaranteeing deadlines requires specific algorithms
- Batch processing — Maximizing throughput is the primary goal
- Multi-user systems — Fairness ensures no user gets starved
When Not to Use
- Simple scripts — Default scheduler is sufficient
- Single-user interactive — System defaults are optimized for this
- Embedded with fixed workload — Custom schedulers add complexity
Types of Scheduling
Non-Preemptive vs Preemptive
Non-preemptive: Once a process starts a CPU burst, it keeps the CPU until that burst finishes or it blocks. The scheduler does not interrupt it just because a shorter or higher-priority job arrives.
Preemptive: The scheduler can interrupt a running task and choose another runnable task. This can improve response time, but adds scheduling and context-switch work. Real operating systems use policies and priorities beyond these classroom rules.
graph LR
subgraph Non-Preemptive
A1[Process A starts] --> A2[A runs to completion]
end
subgraph Preemptive
B1[Process B starts] --> B2[B preempted]
B2 --> C1[Process C runs]
C1 --> B3[B resumes]
end
style Non-Preemptive stroke:#4a1a1a
style Preemptive stroke:#1a3a1a
Core Algorithms
The names below describe textbook policies. FCFS and the usual SJF example are non-preemptive. Shortest Remaining Time First (SRTF) is the preemptive form of SJF. Priority scheduling can be either preemptive or non-preemptive; Round Robin uses a time quantum and is preemptive by design. MLFQ is also a preemptive model, with queue rules that vary by textbook or implementation.
First-Come, First-Served (FCFS)
The simplest algorithm: processes run in the order they arrived.
Pros: Simple, low overhead Cons: Convoy effect — short processes wait behind long ones
// Simulate FCFS scheduling
#include <stdio.h>
typedef struct {
int pid;
int arrival_time;
int burst_time;
} Process;
void fcfs_schedule(Process procs[], int n) {
int current_time = 0;
printf("FCFS Scheduling:\n");
printf("%-10s %-15s %-15s %-15s\n", "PID", "Start Time", "End Time", "Wait Time");
for (int i = 0; i < n; i++) {
int wait = current_time - procs[i].arrival_time;
if (wait < 0) wait = 0;
int start = current_time;
current_time += procs[i].burst_time;
int end = current_time;
printf("%-10d %-15d %-15d %-15d\n", procs[i].pid, start, end, wait);
}
}
Shortest Job First (SJF)
Select the arrived process with the shortest next CPU burst. The usual textbook version is non-preemptive. It minimizes average waiting time when all jobs are available together and their CPU burst lengths are known; real workloads rarely provide that knowledge in advance.
Pros: Optimal average wait time Cons: Starvation of long processes; requires burst time prediction
// Simulate SJF scheduling (non-preemptive)
#include <stdio.h>
#include <limits.h>
void sjf_schedule(Process procs[], int n) {
int completed = 0;
int current_time = 0;
int total_wait = 0;
int remaining = n;
int visited[n];
for (int i = 0; i < n; i++) visited[i] = 0;
printf("\nSJF Scheduling:\n");
printf("%-10s %-15s %-15s %-15s %-15s\n", "PID", "Arrival", "Burst", "Start", "Wait");
while (completed < n) {
int shortest = -1;
int min_burst = INT_MAX;
// Find shortest job that's arrived and not completed
for (int i = 0; i < n; i++) {
if (!visited[i] && procs[i].arrival_time <= current_time &&
procs[i].burst_time < min_burst) {
shortest = i;
min_burst = procs[i].burst_time;
}
}
if (shortest == -1) {
current_time++;
continue;
}
int wait = current_time - procs[shortest].arrival_time;
int start = current_time;
current_time += procs[shortest].burst_time;
int end = current_time;
printf("%-10d %-15d %-15d %-15d %-15d\n",
procs[shortest].pid, procs[shortest].arrival_time,
procs[shortest].burst_time, start, wait);
total_wait += wait;
visited[shortest] = 1;
completed++;
}
printf("Average wait time: %.2f\n", (float)total_wait / n);
}
Shortest Remaining Time First (SRTF)
SRTF is preemptive SJF: whenever a process becomes ready, compare its burst time with the remaining CPU time of the running process. Run the job with the smaller remaining time. It can reduce short-job waiting in a known workload, but a stream of short arrivals can leave a long job waiting. Use aging or periodic promotion in a design that needs a starvation bound.
Round Robin (RR)
Each process gets a fixed time slice (quantum). When the quantum expires, the process goes to the back of the ready queue. Designed for time-sharing.
Pros: Gives each ready process a turn within a cycle when a finite set of peers stays runnable Cons: Higher context switch overhead, depends on quantum size
#!/usr/bin/env python3
"""Round Robin Scheduler Simulation."""
from collections import deque
class Process:
def __init__(self, pid, burst, arrival=0):
self.pid = pid
self.burst = burst
self.arrival = arrival
self.remaining = burst
self.wait_time = 0
self.turnaround = 0
def round_robin(processes, quantum):
ready = deque(processes)
current_time = 0
completed = []
print(f"Round Robin (quantum={quantum}):")
print(f"{'Time':<8} {'Event':<20} {'Ready Queue'}")
while ready:
process = ready.popleft()
if process.arrival > current_time:
# Skip ahead if no processes have arrived
current_time = process.arrival
ready.append(process)
continue
# Execute for quantum or until completion
exec_time = min(quantum, process.remaining)
current_time += exec_time
process.remaining -= exec_time
# Other processes in ready queue wait
for p in ready:
if p.arrival <= current_time:
p.wait_time += exec_time
if process.remaining == 0:
process.turnaround = current_time - process.arrival
completed.append(process)
print(f"{current_time:<8} P{process.pid} completes")
else:
ready.append(process)
print(f"{current_time:<8} P{process.pid} preempted")
return completed
# Example
processes = [Process(1, 24), Process(2, 3), Process(3, 3)]
result = round_robin(processes, 4)
print(f"\n{'PID':<8} {'Burst':<8} {'Wait':<8} {'Turnaround':<12}")
print("-" * 40)
for p in result:
print(f"{p.pid:<8} {p.burst:<8} {p.wait_time:<8} {p.turnaround:<12}")
Priority Scheduling
Processes are assigned priorities. Higher priority processes run first. Two variants:
Preemptive: A new higher-priority process preempts the running one Non-preemptive: Higher priority only matters when current process blocks
Problem: Starvation — low priority processes may never run if higher priority ones keep arriving.
Solution: Aging — gradually increase priority of waiting processes.
// Priority Scheduling with Aging
#include <stdio.h>
#define BASE_PRIORITY 50
#define AGING_INTERVAL 2 // Improve priority once per two waiting time units
typedef struct {
int pid;
int base_priority; // Lower number = higher priority
int dynamic_priority;
int remaining_burst;
int waiting_time;
} Process;
void priority_with_aging(Process procs[], int n) {
printf("\nPriority Scheduling with Aging:\n");
int completed = 0;
int current_time = 0;
while (completed < n) {
// Derive each ready process's priority from its time in the ready queue.
for (int i = 0; i < n; i++) {
if (procs[i].remaining_burst > 0) {
procs[i].dynamic_priority = procs[i].base_priority -
procs[i].waiting_time / AGING_INTERVAL;
if (procs[i].dynamic_priority < 1) {
procs[i].dynamic_priority = 1; // Max priority
}
}
}
// Find highest priority (lowest number)
int highest = -1;
int highest_priority = 999;
for (int i = 0; i < n; i++) {
if (procs[i].remaining_burst > 0 &&
procs[i].dynamic_priority < highest_priority) {
highest = i;
highest_priority = procs[i].dynamic_priority;
}
}
if (highest == -1) {
current_time++;
continue;
}
// Run the chosen process for one unit and reset its ready-queue wait.
printf("Time %d: P%d (priority %d)\n",
current_time, procs[highest].pid, procs[highest].dynamic_priority);
procs[highest].remaining_burst--;
procs[highest].waiting_time = 0;
current_time++;
// Increment wait time for other processes
for (int i = 0; i < n; i++) {
if (i != highest && procs[i].remaining_burst > 0) {
procs[i].waiting_time++;
}
}
if (procs[highest].remaining_burst == 0) {
completed++;
}
}
}
Worked example: SJF and SRTF
This is a classroom calculation, not a performance benchmark. Assume one CPU, no I/O, zero context-switch cost, and these CPU-bound jobs. In non-preemptive SJF, equal burst lengths are ordered by arrival time.
| Process | Arrival | CPU burst |
|---|---|---|
| A | 0 | 7 |
| B | 2 | 4 |
| C | 4 | 1 |
| D | 5 | 4 |
At time 0, only A is ready, so non-preemptive SJF runs it through time 7. B, C, and D have arrived by then; C has the shortest burst. After C finishes, B and D tie at 4, so B runs first because it arrived earlier.
Non-preemptive SJF
0 | A | 7 | C | 8 | B | 12 | D | 16
For SRTF, A runs from 0 to 2. B arrives with 4 units remaining versus A’s 5, so B preempts A. At time 4, C arrives with 1 unit remaining and preempts B. Then B resumes, followed by D and A.
Preemptive SRTF
0 | A | 2 | B | 4 | C | 5 | B | 7 | D | 11 | A | 16
Compute each job’s metrics from the chart:
- Response = first start − arrival.
- Waiting = turnaround − CPU burst for this no-I/O example.
- Turnaround = finish − arrival.
| Policy | Process | First start | Finish | Response calculation | Waiting calculation | Turnaround calculation |
|---|---|---|---|---|---|---|
| SJF | A | 0 | 7 | 0 − 0 = 0 | 7 − 0 − 7 = 0 | 7 − 0 = 7 |
| SJF | B | 8 | 12 | 8 − 2 = 6 | 10 − 4 = 6 | 12 − 2 = 10 |
| SJF | C | 7 | 8 | 7 − 4 = 3 | 4 − 1 = 3 | 8 − 4 = 4 |
| SJF | D | 12 | 16 | 12 − 5 = 7 | 11 − 4 = 7 | 16 − 5 = 11 |
| SRTF | A | 0 | 16 | 0 − 0 = 0 | 16 − 0 − 7 = 9 | 16 − 0 = 16 |
| SRTF | B | 2 | 7 | 2 − 2 = 0 | 5 − 4 = 1 | 7 − 2 = 5 |
| SRTF | C | 4 | 5 | 4 − 4 = 0 | 1 − 1 = 0 | 5 − 4 = 1 |
| SRTF | D | 7 | 11 | 7 − 5 = 2 | 6 − 4 = 2 | 11 − 5 = 6 |
Average the four rows for each policy. SJF gives average response 16/4 = 4, average waiting 16/4 = 4, and average turnaround 32/4 = 8 time units. SRTF gives 2/4 = 0.5, 12/4 = 3, and 28/4 = 7, respectively. These results describe only this declared workload; changing arrivals, burst estimates, I/O, or context-switch cost can change the comparison.
Multi-Level Feedback Queue (MLFQ)
MLFQ is a textbook adaptive policy with queues at different priorities and time quanta. In this model, a process that uses its full quantum may move to a lower queue, while an early block may keep it near the top. Queue rules vary by model; this is not a description of Linux’s default policy.
graph TB
subgraph Q1[Queue 1 - Highest Priority]
A1[Interactive<br/>Quantum: 8ms]
end
subgraph Q2[Queue 2 - Medium Priority]
B1[Mixed<br/>Quantum: 16ms]
end
subgraph Q3[Queue 3 - Lowest Priority]
C1[Batch<br/>Quantum: 32ms]
end
A1 -->|Uses full quantum| B1
B1 -->|Uses full quantum| C1
C1 -->|Blocked I/O| A1
A1 -->|Shorter quantum| Scheduler
B1 -->|Medium quantum| Scheduler
C1 -->|Longer quantum| Scheduler
Scheduler -->|picks highest non-empty| A1
Scheduler -->|picks highest non-empty| B1
Scheduler -->|picks highest non-empty| C1
style Q1 stroke:#1a4a1a
style Q2 stroke:#1a1a4a
style Q3 stroke:#4a1a1a
The 8, 16, and 32 ms quanta in this diagram are illustrative model values, not settings for a current operating system.
Production Failure Scenarios
Convoy Effect in FCFS
Problem: A long CPU-bound process blocks short I/O-bound processes. Short jobs wait while long job holds CPU.
Symptoms: System appears responsive at first, then slows as long jobs dominate.
Mitigation: Use Round Robin or SJF to give short jobs priority.
The convoy effect hides under light load. Say you have three processes: P1 (100ms CPU-bound), P2 (5ms I/O-bound), P3 (5ms I/O-bound). P1 arrives at t=0, P2 at t=1, then immediately blocks on disk I/O while P1 runs. By the time P2’s I/O completes at t=50, P1 is still burning CPU. P2 waits 49ms for a 5ms job. The I/O device sits idle the whole time.
The fix is recognizing that CPU-bound and I/O-bound processes have fundamentally different needs. I/O-bound processes need brief CPU windows to dispatch I/O requests and process results, they do not need long CPU bursts. Round Robin with a modest quantum gives these processes enough CPU to stay productive. SJF prioritizes short jobs by definition. MLFQ handles this automatically: I/O-bound processes drop their quantum usage and stay in high-priority queues, while CPU-bound jobs sink to lower queues with longer time slices.
Starvation in Priority Scheduling
Problem: Low priority processes never get CPU time as high priority processes keep arriving.
Symptoms: Certain processes show extremely high wait times, never completing.
Mitigation: Implement aging — increase priority of waiting processes over time.
In theory, high priority work gets done first. In practice, if high-priority work keeps arriving, low-priority processes queue up forever. This happens in production: a logging daemon at low priority gets buried under user request handlers during traffic spikes. The logs never flush. Insidious because the system looks fine under light load.
Aging treats wait time as a priority boost. For example, suppose lower numbers mean higher priority, a low-priority job starts at priority 5, and priority-1 jobs keep arriving with one-unit bursts. If the model improves a waiting job’s priority by one level every two time units and breaks ties by arrival order, the waiting job reaches priority 1 after eight units and runs before newer jobs at that level. Without aging or a queue-wide priority boost, strict priority can starve it. This is a textbook mitigation; Linux’s fair scheduler has different accounting and is not this priority-aging algorithm.
Quantum Too Small
Problem: Excessive context switches consume more CPU than useful work.
Symptoms: High system CPU utilization but low throughput, high context switch rate.
Mitigation: Profile with perf sched and adjust quantum. Rule: quantum should be 10x context switch cost.
Context-switch cost varies with the processor, kernel, workload, and what state must be restored. Do not treat a fixed microsecond figure as a property of the scheduler. Measure overhead on the target machine, and remember that cache and TLB effects can outlast the switch itself.
The real cost is not just the switch time, it is cache pollution. When you switch to a new process, the CPU L1/L2 caches and TLB entries get invalidated. The new process starts with cold caches, spending the first portion of its quantum loading code and data back in. If the quantum expires before the process gets useful work done, you are paying cache-fill cost for almost no useful computation. The sweet spot is a quantum large enough that processes complete meaningful work between switches, but small enough that interactive latency stays low.
Quantum Too Large
Problem: System feels unresponsive; long processes block short ones.
Symptoms: Poor response time for interactive tasks despite idle CPU.
**Mitigation: Smaller quantum or combination of algorithms (interactive vs batch).
When quantum balloons, the scheduler starts acting like FCFS. A process that arrives just after a long job started waits nearly the entire quantum before getting a turn. Interactive users notice: they press a key and nothing happens for hundreds of milliseconds while the currently-running process finishes its time slice.
The fix is not always to make every quantum smaller. Some textbook workloads benefit from longer slices because they spend less time switching, while interactive work benefits from a shorter wait before its next turn. A hybrid model can give interactive tasks a short slice and batch jobs a longer one. These are model choices; Linux’s default fair policy is not a fixed-round-robin queue with a universal quantum.
Measuring Scheduling Performance
Linux exposes scheduling policies through interfaces such as sched(7) and task-level state through /proc/<pid>/sched. For a trace, perf sched record captures scheduler events and perf sched timehist summarizes when tasks ran. Details and available tracepoints depend on the kernel and installed tools; the kernel’s EEVDF documentation describes the current fair-scheduler direction.
The r column in vmstat 1 reports runnable work, not a universal overload threshold. Compare it with available CPUs, per-core utilization, and application latency. A single pinned core with idle capacity elsewhere may point to a single-threaded workload or affinity constraint; confirm before changing scheduler settings.
There is no workload-independent ranking for these models. The worked SJF/SRTF trace above gives exact results for its declared arrivals and CPU bursts. For another workload, draw the schedule and calculate response, waiting, and turnaround from its own trace. Utilization and throughput also depend on the workload and elapsed-time window, so avoid assigning them a generic “best algorithm” label.
In a Round Robin model, a smaller quantum gives another ready task a turn sooner but causes more switches. A larger quantum reduces switches while increasing the wait before a new task can run. Those are model tradeoffs; Linux’s default SCHED_OTHER policy has no fixed Round Robin quantum to tune.
Implementation Snippets
Implementing a Simple MLFQ
#!/usr/bin/env python3
"""Multi-Level Feedback Queue Scheduler."""
from collections import deque
class Process:
def __init__(self, pid, burst, priority=0):
self.pid = pid
self.burst = burst
self.priority = priority # 0 = highest
self.remaining = burst
class MLFQScheduler:
def __init__(self, num_queues=3, quantums=[8, 16, 32]):
self.queues = [deque() for _ in range(num_queues)]
self.quantums = quantums
def add_process(self, proc):
self.queues[proc.priority].append(proc)
def schedule(self):
time = 0
completed = []
while True:
# Find highest non-empty queue
chosen = None
for i, q in enumerate(self.queues):
if q:
chosen = (i, q.popleft())
break
if chosen is None:
break
q_idx, proc = chosen
quantum = self.quantums[q_idx]
# Execute for quantum or until completion
exec_time = min(quantum, proc.remaining)
time += exec_time
proc.remaining -= exec_time
if proc.remaining == 0:
proc.turnaround = time
completed.append(proc)
print(f"Time {time}: P{proc.pid} completed")
else:
# Demote to lower priority (next queue)
next_q = min(q_idx + 1, len(self.queues) - 1)
proc.priority = next_q
self.queues[next_q].append(proc)
print(f"Time {time}: P{proc.pid} demoted to Q{next_q}")
return completed
# Example
scheduler = MLFQScheduler()
processes = [
Process(1, 20), # Interactive (will get demoted if CPU-bound)
Process(2, 10), # Short interactive
Process(3, 40), # Long batch
]
for p in processes:
scheduler.add_process(p)
results = scheduler.schedule()
Measuring Scheduling Performance in Practice
#!/bin/bash
# Measure scheduling performance metrics
echo "=== Scheduler Information ==="
uname -r
chrt -p "${PID:?Set PID to a process or thread ID}"
cat "/proc/${PID}/sched"
echo -e "\n=== Context Switches ==="
cat /proc/stat | grep ctxt
echo -e "\n=== Run Queue Length ==="
vmstat 1 5
echo -e "\n=== Process State ==="
ps -eo state,pid,cmd | sort | uniq -c | sort -rn
echo -e "\n=== Scheduler Trace ==="
sudo perf sched record -- sleep 5
sudo perf sched timehist
Observability Checklist
Key Metrics
# CPU utilization per core
mpstat -P ALL 1
# Run queue length; interpret it alongside available CPU capacity
vmstat 1
# Context switches per second
sar -w 1
# Task scheduling state (set PID to a process or thread ID)
cat "/proc/${PID}/sched"
Tracing
# Trace scheduling decisions
sudo perf trace -e sched:*
# Scheduler latency histogram
perf sched record -- sleep 10
perf sched timehist
# Per-process scheduling info
ps -eo pid,psr,ni,time,cmd --sort=-time
Common Pitfalls / Anti-Patterns
Security Pitfalls
Misconfigured scheduling permissions can give one workload more CPU share than intended or let real-time work delay ordinary tasks. Check the process’s policy and permissions before treating this as a scheduler bug.
Processes need permission to set negative nice values or use real-time policies. A runnable real-time task can outrank ordinary tasks; SCHED_FIFO runs until it blocks, yields, completes, or a higher-priority real-time task preempts it. SCHED_RR also rotates threads of equal real-time priority after its quantum. See sched(7).
Priority Manipulation Attacks
Use RLIMIT_NICE, capabilities, and service-manager policy to control who may lower a task’s nice value. The exact configuration depends on the distribution and deployment environment.
Real-time Process Security
Restrict access to real-time scheduling policies and check bandwidth or cgroup controls. A task in a real-time policy can delay ordinary tasks even when its code is not doing useful work.
Operational Pitfalls
Scheduler misconfiguration is one of those issues that shows up as “slowness” in monitoring but takes forever to trace back to the actual cause. Quantum misconfiguration, wrong assumptions about burst times, and ignoring I/O blocking behavior are the usual suspects. These mistakes slip past QA because they only manifest under specific workloads or at scale.
These pitfalls often come from applying a classroom model directly to a production system. A Round Robin quantum that works for one simulation may not fit another workload. SJF also assumes burst lengths are known. On multicore systems, CPU placement and affinity add another constraint: a narrow affinity mask can leave available capacity unused.
Tuning a model’s quantum
In a Round Robin simulation, choose a quantum based on the declared workload and response target.
Textbook quantum tuning is for Round Robin models. Linux’s default SCHED_OTHER policy does not expose one fixed quantum for all tasks. If a workload has a latency target, measure its scheduling delay and application response times before changing policy or CPU controls.
Use perf sched record and perf sched timehist to inspect when runnable tasks get CPU time. Compare run-queue delay and application response-time percentiles with the workload’s target. A long wait can come from CPU contention, affinity restrictions, cgroup limits, or the selected policy; Linux’s default fair policy does not expose a universal Round Robin quantum to tune.
Using SJF Without Burst Prediction
In production, exact future burst times are not usually known. MLFQ is one textbook heuristic for adapting to observed behavior, not a general replacement for an operating system’s scheduler.
SJF’s theoretical result assumes you know each job’s next CPU burst. In practice, estimates from prior runs can be wrong: a batch step that usually takes 100 ms may take longer after a slow disk read. In a textbook MLFQ model, queue position adapts to whether a job uses its quantum or blocks early. Current OS policies use their own accounting and should be measured directly.
If a production system needs latency or fairness guarantees, measure its workload and choose an operating-system policy or resource control that matches those needs. A textbook SJF burst estimate is not the same thing as Linux’s current fair-scheduling implementation.
Forgetting About I/O Blocking
I/O-bound processes are often blocked, then need CPU time after they wake. Do not assume a CPU scheduling change will fix an I/O wait.
I/O-bound processes need very little CPU time, but they need it immediately when their I/O completes. A disk I/O request might take 10ms, but if the process waits another 20ms for CPU to process the result, you have doubled your latency for no reason. The fix is recognizing that runnable does not mean CPU-hungry. An interactive shell that blocks on keyboard input for 95% of its life still needs sub-millisecond response time when input arrives.
The naive approach is to assign higher static CPU priority to every I/O-bound task. That can starve lower-priority work when those tasks remain runnable. In the textbook MLFQ model, a task that blocks early may stay in a higher queue, while one that uses its full quantum may move down. I/O priority settings such as ionice affect block I/O scheduling; they do not give a task higher CPU priority.
Not Considering Multi-Core
Single queue vs per-CPU queues have different tradeoffs for cache affinity vs contention.
Modern kernels use per-CPU scheduling structures and balancing mechanisms, but their details change across versions and policy classes. Do not assume that binding every task to a core will improve throughput; affinity can also leave capacity idle or make load imbalance worse.
The tradeoff is cache affinity. A process that runs on core 0 has its data in core 0’s cache. Move it to core 1 and that cache is cold. Per-CPU queues naturally keep processes on the same core unless that core is overloaded, preserving cache warmth. The performance difference is significant: a cache hit might take 4 cycles; a cache miss off DRAM, 200+. For a process that touches lots of data, a database or web server, keeping it on one core can be worth more than load balancing across all cores.
Quick Recap Checklist
- FCFS is simple but causes convoy effect
- SJF minimizes average wait but requires knowing burst times
- Round Robin is fair with good response time; quantum size matters
- Priority scheduling has starvation; use aging to mitigate
- MLFQ combines multiple algorithms, dynamically adjusting
- Quantum too small = excessive context switches; too large = poor response
- No single algorithm is best — trade-offs depend on workload
Interview Questions
Non-preemptive scheduling means once a process starts running, it runs to completion (or until it voluntarily blocks). The scheduler only makes decisions when the running process blocks or terminates.
Preemptive scheduling allows the OS to forcibly interrupt a running process and switch to another. This happens on timer interrupts, when a higher priority process becomes ready, or based on time slice expiration.
Preemptive scheduling lets the kernel regain control without waiting for a task to yield. It supports interactive response, though actual scheduling depends on policy and resource constraints:
- A long-running calculation can be interrupted so another runnable task can run
- A higher scheduling class can preempt a lower class when its policy allows
- Preemption alone does not guarantee a fixed share or response deadline
Linux exposes several scheduling policies; see sched(7) for their rules. Kernel configuration and scheduling class affect when preemption occurs.
The convoy effect occurs in FCFS when a long CPU-bound process ahead causes short I/O-bound processes to wait, even though the I/O devices are idle. The long process holds the CPU while the short processes wait with idle I/O.
Example: Process A (100ms CPU) arrives before Process B (1ms CPU). B arrives just after A starts. B must wait 100ms while A uses CPU, even though B could complete in 1ms.
Mitigations:
- Round Robin: Each process gets quantum time; short jobs complete faster
- SJF: Short jobs run first, minimizing wait time (but requires knowing burst times)
- Priority scheduling: Give I/O-bound processes higher priority
- MLFQ: I/O-bound processes naturally stay in high-priority queues
MLFQ uses multiple queues with different priorities and time quantum sizes:
- High priority queue: Short quantum (4-8ms) for interactive processes
- Medium priority: Medium quantum (16-32ms)
- Low priority: Long quantum or FCFS for batch jobs
How it works:
- New processes enter the highest priority queue
- If a process uses its entire quantum, it's demoted to a lower queue
- If a process blocks before using its quantum, it stays in the current queue (or moves up)
- When a process in a higher queue becomes ready, it preempts lower ones
Result: Interactive processes (short bursts, frequent I/O) stay in high-priority queues with quick response. CPU-bound batch jobs naturally sink to lower queues but get longer time slices when they do run.
A context switch uses CPU time to save and restore task state, and can disrupt cache locality. Its cost depends on hardware, kernel, and workload, so measure it if it matters to the design.
In a Round Robin model, a smaller quantum improves the maximum wait for another turn but causes more switches. A larger quantum reduces switches but makes a newly ready task wait longer. Choose a value from the stated workload and response target rather than a universal rule.
These quantum rules describe Round Robin models. Linux's default SCHED_OTHER policy does not use a fixed Round Robin quantum; SCHED_RR is a separate real-time policy.
When comparing model runs:
- State the arrival times, burst lengths, and quantum
- Include or exclude switch cost consistently
- Report response time alongside waiting and turnaround time
Starvation (also called indefinite postponement) occurs when a process never gets scheduled because other processes keep getting priority. In priority scheduling, low-priority processes can wait forever if high-priority tasks keep arriving.
Aging is a technique to prevent starvation by gradually increasing the priority of waiting processes over time. The longer a process waits, the higher its priority becomes, until eventually it gets scheduled.
Example: with lower numbers meaning higher priority, a job starting at priority 5 and moving up one level every two time units reaches priority 1 after eight waiting units. If equal priorities are ordered by arrival, it can run ahead of later arrivals at priority 1.
Linux's fair scheduling uses a different accounting model. Kernel documentation describes the transition from CFS toward EEVDF, which tracks task lag and virtual deadlines. That is not textbook priority aging, and other scheduling policies or CPU resource limits can change how soon a task runs.
The convoy effect occurs when one or more CPU-bound processes monopolize the CPU, causing I/O-bound processes to wait even though the I/O devices are idle. The I/O-bound processes make a request, get scheduled briefly, block on I/O immediately, and then wait while the CPU-bound process completes its burst.
This creates a convoy of I/O requests behind a slow CPU-bound leader. The system appears sluggish despite having plenty of CPU capacity because I/O-bound processes complete quickly when they get CPU but are rarely given the chance.
Mitigation: Use SJF or Round Robin to give shorter jobs priority. MLFQ naturally handles this — I/O-bound processes stay in high-priority queues and get frequent short time slices.
MLFQ prevents starvation through two mechanisms: aging and queue promotion.
Aging: If a process stays in a lower queue for too long without being scheduled, its priority is gradually boosted, moving it to a higher queue. This ensures that even low-priority CPU-bound jobs eventually get CPU time.
Queue promotion: Some MLFQ implementations periodically promote all processes to the highest priority queue, ensuring that long-waiting processes are given a chance to run at high priority.
The key insight is that MLFQ assumes processes will be CPU-bound or I/O-bound — CPU-bound jobs naturally sink to lower queues, while I/O-bound jobs stay in high queues. Without aging, truly CPU-only jobs could be stuck at the bottom forever.
Scheduling overhead is the CPU time spent deciding which process to run and performing the context switch, rather than doing useful work.
In a Round Robin model, a smaller quantum means more frequent switches and can reduce the wait for a new arrival. A larger quantum reduces switching but can delay a ready task behind the current slice. The right tradeoff depends on the workload and response target.
Linux's default SCHED_OTHER policy is not fixed Round Robin. Linux provides SCHED_RR as a separate real-time policy; see sched(7) for the policy-specific rules.
Turnaround time = time from job submission to time of completion. It includes waiting time plus actual execution time plus any I/O time.
Waiting time = time spent in the ready queue, not executing. It excludes the actual execution time and I/O wait.
A scheduler optimizing for turnaround time might give long jobs more CPU upfront (FCFS), which increases waiting time for short jobs. A scheduler optimizing for waiting time (SJF) might reduce turnaround time but could starve long jobs.
Important: only waiting time is directly under the scheduler's control. Turnaround time depends on both scheduling decisions and the process's own behavior (I/O patterns, burst lengths).
MLFQ learns by observing whether a process uses its entire time quantum or blocks before it expires:
- Uses full quantum (CPU-bound): MLFQ assumes the process needs heavy computation and demotes it to a lower priority queue with a longer quantum.
- Blocks before quantum expires (I/O-bound): MLFQ assumes the process is interactive and keeps it in the current queue or promotes it to a higher priority queue.
This feedback-driven approach means MLFQ starts with no knowledge of a process and adapts based on observed behavior. A long-running batch job will be demoted over time; an interactive shell remains at high priority.
The tradeoff is that MLFQ can be gamed — a malicious process could periodically perform I/O to stay at high priority and monopolize CPU.
Fair share scheduling ensures that each user or group receives a fair proportion of CPU time, regardless of how many processes they have running. For example, if user A has 10 processes and user B has 1 process, both users get 50% of CPU (not user A getting 91% because they have more processes).
Fair-share scheduling can account for groups as well as individual tasks. Linux CPU cgroups can distribute CPU bandwidth among groups, while nice values affect task scheduling within the applicable policy. These controls are separate from textbook SJF or Round Robin algorithms.
Linux SCHED_DEADLINE uses EDF scheduling with runtime, deadline, and period parameters. Each task specifies:
- Runtime: Maximum CPU time needed per period (worst-case execution time)
- Deadline: Time by which execution must complete
- Period: Interval between successive task invocations
The kernel applies admission checks to the configured reservations. Passing those checks does not guarantee an application's end-to-end deadline under every workload or hardware condition; kernel configuration, blocking, interrupts, and work outside the scheduled task also matter. See the policy details in the Linux sched(7) manual.
Hard real-time: A missed deadline is a system failure. The task must complete by its deadline or the result is useless or dangerous. Examples include flight-control and safety systems. A scheduler policy alone does not establish a hard real-time guarantee; the whole system needs analysis against its timing requirements.
Soft real-time: Missing a deadline reduces quality but the system continues operating. Video playback dropping frames, audio glitching, or a trading system missing an arbitrage window are soft real-time failures. SCHED_FIFO and SCHED_RR provide soft real-time behavior — high priority but no formal deadline guarantee.
Key difference: hard real-time requires formal verification that the system can meet all deadlines under worst-case conditions. Soft real-time uses priority and FIFO/RR policies to minimize missed deadlines but doesn't guarantee them.
Priority inversion: High-priority task H is blocked waiting for a lock held by low-priority task L. Medium-priority task M preempts L, delaying H's lock release indefinitely.
Priority inheritance: When H blocks on a lock held by L, L's priority is temporarily raised to H's priority (or higher if there are multiple waiting tasks). This prevents M from preempting L while L holds the lock needed by H.
The inheritance chain can be transitive: if L holds another lock that a higher priority task H2 wants, L's priority gets raised to H2's level. When L releases the lock, its priority reverts.
Linux implements priority inheritance for mutexes via PI-futexes. Not all locks support it — only those explicitly implemented with PI-futexes. Priority inheritance adds overhead, so it is not enabled by default for all synchronization primitives.
In priority-based Round Robin, the scheduler first selects the highest priority non-empty queue. All processes in that queue are scheduled in round-robin fashion with time quantum appropriate for that priority level.
Lower priority queues only receive CPU time when all higher priority queues are empty. This is why high-priority interactive processes get excellent response time — they are always scheduled first.
The tradeoff is that lower priority batch jobs may starve if higher priority processes are always runnable. This is addressed by periodically boosting starving processes' priority (aging) or using a more sophisticated multi-level queue that considers both priority and wait time.
Scheduler latency (scheduling latency) is the time between a process becoming runnable (e.g., I/O completing) and it actually starting to run on a CPU. System responsiveness is how quickly the system reacts to user actions.
For an interactive application (e.g., a shell command), responsiveness means the time between pressing Enter and seeing output. This depends on the shell process being scheduled, not just the CPU-bound work. Even if the CPU is busy, interactive processes need to be scheduled quickly to maintain the feeling of responsiveness.
Reducing the time a runnable task waits can improve response, but how to do that depends on the kernel's policy, contention, affinity, and CPU limits. Linux's default time-sharing policy does not expose a universal Round Robin quantum; see the current kernel's fair-scheduler documentation and sched(7).
Linux kernel documentation says the fair scheduler began transitioning from CFS to EEVDF in Linux 6.6. EEVDF tracks a task's virtual runtime and lag; among eligible tasks it selects by virtual deadline. The exact implementation depends on the kernel version. See the Linux 7.0 EEVDF documentation.
This is distinct from textbook Round Robin: normal Linux time-sharing does not rotate every runnable task through one fixed time quantum. Linux also provides a separate SCHED_RR policy for real-time threads.
Linux defines scheduling classes (struct sched_class) that plug into the scheduler. Each class implements a common interface: enqueue, dequeue, pick_next, yield, etc.
Linux has scheduler classes for deadline, real-time, fair, and idle tasks, among others. The fair class has been transitioning from CFS toward EEVDF; the exact order and implementation details are kernel-specific. The public policies include SCHED_OTHER, SCHED_BATCH, SCHED_IDLE, SCHED_FIFO, SCHED_RR, and SCHED_DEADLINE.
Linux uses scheduling classes and policy-specific ordering. The policy documentation describes the relative behavior; do not infer a fixed Round Robin order for normal time-sharing tasks from the textbook examples.
SCHED_OTHER is the API policy name; Linux source code also calls it SCHED_NORMAL. SCHED_BATCH and SCHED_IDLE are distinct policies for normal, non-real-time scheduling. The fair scheduling implementation behind them depends on the kernel version. SCHED_RR is a separate real-time policy that rotates threads of equal real-time priority after a time quantum. See sched(7).
CPU overcommit means the hypervisor assigns more virtual CPUs to VMs than physical CPUs exist. The hypervisor scheduler must time-share physical CPUs among vCPUs.
When a vCPU is ready to run but no physical CPU is available, the hypervisor schedules another vCPU. This causes scheduling latency and reduced determinism. Real-time tasks inside VMs suffer because the hypervisor introduces an extra scheduling layer.
Mitigations: Use CPU affinity to pin vCPUs to physical cores, reducing hypervisor scheduling overhead. Use real-time scheduling classes for critical VMs. Reserve some physical cores for real-time workloads so they are not stolen by overcommitted VMs.
Further Reading
- Process Scheduling — General scheduling theory, context switching, and scheduler types
- CPU Affinity & Real-Time OS — Real-time scheduling policies (SCHED_FIFO, SCHED_RR, SCHED_DEADLINE)
- EEVDF Scheduler — Linux Kernel 7.0 — Current fair-scheduler direction and task eligibility
- sched(7) — Linux manual — Linux scheduling policies, including
SCHED_RR - Multilevel Feedback Queue Scheduling — IBM Research — Original MLFQ paper by Corbató et al.
Conclusion
Process scheduling algorithms are the mechanism by which operating systems decide which runnable process gets CPU time. The choice of algorithm profoundly impacts system responsiveness, throughput, and fairness.
FCFS is simple but vulnerable to the convoy effect, where short processes wait behind long ones. SJF minimizes average waiting time under its textbook assumptions, but requires burst-time knowledge and can starve long processes. Round Robin gives each continuously ready process a turn in a finite queue; its quantum trades quicker response for more frequent switching.
Priority scheduling lets selected work run first, but low-priority jobs can starve without aging or another mitigation. Textbook MLFQ models adapt queue position to observed CPU use. Current operating systems use their own policies and implementations; on Linux, the default SCHED_OTHER policy is not fixed Round Robin. The kernel’s fair-scheduling path has been transitioning from CFS toward EEVDF, while SCHED_RR remains a separate real-time policy.
For your next step, explore CPU interrupts and context switches to understand the mechanics of how the scheduler actually transfers control between processes, or dive into synchronization primitives (mutexes, semaphores, condition variables) which protect shared data in concurrent multi-threaded environments.
Category
Related Posts
ASLR & Stack Protection
Explore ASLR, PIE, stack canaries, and NX on Linux with GCC, then inspect a harmless C program to see what each mitigation does and where it falls short.
Assembly Language Basics: Writing Code the CPU Understands
Learn x86-64 Linux assembly with the System V ABI: track registers, assemble and run a small program, debug it in GDB, then compare AArch64.
Boolean Logic & Gates
Understanding AND, OR, NOT gates and how they combine into arithmetic logic units — the building blocks of every processor.