Repository navigation
Operating Systems 04 scheduling
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Scheduling (computing)
- Wikipedia: Round-robin scheduling
- Wikipedia: Multilevel feedback queue
- Wikipedia: Completely Fair Scheduler
- Book: Silberschatz, Galvin and Gagne, Operating System Concepts, chapter 5
There are usually more ready threads than CPU cores. The scheduler is the part of the kernel that decides which ready thread runs next, and for how long. Different rules favour different goals: finishing jobs quickly on average, responding fast to the user, or being fair. Working out a schedule by hand on a Gantt chart is one of the most common OS interview questions.
All schedules on this page were worked out by hand for one example and re-checked; they are illustrative.
This page covers the metrics (turnaround, waiting, response time), preemptive versus non-preemptive scheduling, FCFS, SJF, SRTF, Round Robin, priority scheduling with aging, multilevel feedback queues, a short note on Linux's scheduler, and a full worked example. Process states are on Processes.
| Checkout rule | Scheduling algorithm |
|---|---|
| Serve people in the order they joined | FCFS |
| Let the person with the fewest items go first | SJF |
| Let anyone with fewer items than the person being served jump in | SRTF |
| Serve each person for 1 minute, then send them to the back of the queue | Round Robin |
| Serve VIPs first | Priority |
| VIPs first, but anyone who has waited long becomes a VIP | Priority with aging |
| Measure | Formula | Who cares |
|---|---|---|
| Turnaround time (TAT) | Completion time − arrival time | Batch jobs: "how long until my job finished?" |
| Waiting time | Turnaround − burst time (time spent in the ready queue) | Most textbook questions |
| Response time | First time on the CPU − arrival time | Interactive users |
| Throughput | Jobs finished per unit time | Servers |
| CPU utilisation | Fraction of time the CPU is busy | Everyone |
A burst is how long a job needs the CPU before it finishes or blocks.
flowchart TD
R["A thread is running"] --> Q{"Can the scheduler take<br/>the CPU away before it<br/>finishes or blocks?"}
Q -->|"No"| NP["Non-preemptive<br/>FCFS, SJF"]
Q -->|"Yes, on a timer or<br/>a better arrival"| P["Preemptive<br/>SRTF, Round Robin,<br/>preemptive priority"]
Every general-purpose OS today is preemptive: a hardware timer interrupt returns control to the kernel regularly so one thread cannot hog the CPU.
| Algorithm | Picks | Preemptive? | Strength | Weakness |
|---|---|---|---|---|
| FCFS (first come, first served) | Earliest arrival | No | Simple, no starvation | Convoy effect: short jobs stuck behind a long one |
| SJF (shortest job first) | Shortest burst among arrived jobs | No | Minimum average waiting time (non-preemptive) | Needs burst lengths in advance; long jobs can starve |
| SRTF (shortest remaining time first) | Shortest remaining time; re-check on every arrival | Yes | Lowest average waiting time overall | Same as SJF, plus more switches |
| Round Robin (RR) | Next in queue, for at most one quantum q | Yes | Good response time, fair, no starvation | Higher average turnaround; overhead if q is tiny |
| Priority | Highest priority | Either | Lets important work go first | Starvation of low priority; fix with aging |
| MLFQ | Highest non-empty queue; demote CPU hogs | Yes | Favours interactive jobs without knowing bursts | Many parameters to tune |
Sources: Wikipedia: Scheduling (computing)
Four processes:
| Process | Arrival | Burst |
|---|---|---|
| P1 | 0 | 8 |
| P2 | 1 | 4 |
| P3 | 2 | 9 |
| P4 | 3 | 5 |
The method is the same for every algorithm:
flowchart LR
A["Draw the Gantt chart<br/>time by time"] --> B["Read each process's<br/>completion time"]
B --> C["TAT = completion − arrival"]
C --> D["Waiting = TAT − burst"]
D --> E["Average over all processes"]
| P1 | P2 | P3 | P4 |
0 8 12 21 26
| Process | Completion | TAT | Waiting |
|---|---|---|---|
| P1 | 8 | 8 | 0 |
| P2 | 12 | 11 | 7 |
| P3 | 21 | 19 | 10 |
| P4 | 26 | 23 | 18 |
| Average | 15.25 | 8.75 |
At time 0 only P1 has arrived, so it runs to the end. At time 8 the shortest of P2 (4), P3 (9), P4 (5) is P2, then P4, then P3.
| P1 | P2 | P4 | P3 |
0 8 12 17 26
| Process | Completion | TAT | Waiting |
|---|---|---|---|
| P1 | 8 | 8 | 0 |
| P2 | 12 | 11 | 7 |
| P3 | 26 | 24 | 15 |
| P4 | 17 | 14 | 9 |
| Average | 14.25 | 7.75 |
| Time | Event | Remaining times | Runs |
|---|---|---|---|
| 0 | P1 arrives | P1=8 | P1 |
| 1 | P2 arrives | P1=7, P2=4 | P2 (4 < 7, preempts P1) |
| 2 | P3 arrives | P1=7, P2=3, P3=9 | P2 |
| 3 | P4 arrives | P1=7, P2=2, P3=9, P4=5 | P2 |
| 5 | P2 done | P1=7, P3=9, P4=5 | P4 |
| 10 | P4 done | P1=7, P3=9 | P1 |
| 17 | P1 done | P3=9 | P3 |
| 26 | P3 done |
|P1| P2 | P4 | P1 | P3 |
0 1 5 10 17 26
| Process | Completion | TAT | Waiting |
|---|---|---|---|
| P1 | 17 | 17 | 9 |
| P2 | 5 | 4 | 0 |
| P3 | 26 | 24 | 15 |
| P4 | 10 | 7 | 2 |
| Average | 13.00 | 6.50 |
Convention: a process arriving during a quantum joins the queue before the process that was just preempted.
| Time slice | Runs | Remaining after | Ready queue after |
|---|---|---|---|
| 0-4 | P1 | P1=4 | P2, P3, P4, P1 |
| 4-8 | P2 | P2 done | P3, P4, P1 |
| 8-12 | P3 | P3=5 | P4, P1, P3 |
| 12-16 | P4 | P4=1 | P1, P3, P4 |
| 16-20 | P1 | P1 done | P3, P4 |
| 20-24 | P3 | P3=1 | P4, P3 |
| 24-25 | P4 | P4 done | P3 |
| 25-26 | P3 | P3 done |
| P1 | P2 | P3 | P4 | P1 | P3 |P4|P3|
0 4 8 12 16 20 24 25 26
| Process | Completion | TAT | Waiting | Response |
|---|---|---|---|---|
| P1 | 20 | 20 | 12 | 0 |
| P2 | 8 | 7 | 3 | 3 |
| P3 | 26 | 24 | 15 | 6 |
| P4 | 25 | 22 | 17 | 9 |
| Average | 18.25 | 11.75 | 4.50 |
| Algorithm | Avg turnaround | Avg waiting | Avg response |
|---|---|---|---|
| FCFS | 15.25 | 8.75 | 8.75 |
| SJF | 14.25 | 7.75 | 7.75 |
| SRTF | 13.00 | 6.50 | 4.25 |
| RR (q = 4) | 18.25 | 11.75 | 4.50 |
SRTF wins on averages, as theory says it must, but only because it knew every burst length in advance. RR has the worst turnaround but its response time does not depend on knowing anything, and it guarantees each process gets the CPU within (n − 1) × q of waiting. For non-preemptive algorithms response time equals waiting time.
Sources: Wikipedia: Round-robin scheduling
flowchart LR
S["Quantum too small"] -->|"many context switches,<br/>overhead dominates"| M["Good quantum<br/>a bit longer than<br/>most interactive bursts"]
L["Quantum too large"] -->|"behaves like FCFS,<br/>poor response"| M
A common rule of thumb is that about 80% of CPU bursts should finish within one quantum.
Each process has a priority number (in many textbooks a smaller number means higher priority). The danger is starvation: a steady stream of high-priority work means low-priority work never runs. Aging raises the priority of a process the longer it waits, so eventually it runs.
The scheduler doesn't know burst lengths, so MLFQ learns them from behaviour:
flowchart TD
N["New job"] --> Q0["Queue 0: highest priority, q = 8 ms"]
Q0 -->|"used whole quantum<br/>(looks CPU-bound)"| Q1["Queue 1: q = 16 ms"]
Q1 -->|"used whole quantum"| Q2["Queue 2: lowest, FCFS"]
Q0 -->|"blocked for I/O early<br/>(looks interactive): stays"| Q0
Q2 -->|"periodic priority boost<br/>(prevents starvation)"| Q0
Rules: run the highest non-empty queue; a job that uses its whole quantum is demoted; a job that gives up the CPU early stays; every so often all jobs are boosted back to the top. Interactive jobs stay at high priority and respond quickly, while CPU-heavy jobs sink.
Sources: Wikipedia: Multilevel feedback queue
For ordinary threads, Linux long used the Completely Fair Scheduler (CFS). It tracks each thread's virtual runtime (CPU time used, scaled by its nice weight) in a red-black tree and always runs the thread with the smallest virtual runtime, so CPU time is shared in proportion to weight. Since kernel 6.6 the default fair scheduler is EEVDF, which keeps the same weighted-fairness idea and adds a deadline to favour latency-sensitive threads. Real-time threads (SCHED_FIFO, SCHED_RR) use fixed priorities and always beat ordinary threads.
Sources: Wikipedia: Completely Fair Scheduler
| Idea | Meaning |
|---|---|
| Per-core run queues | Each core has its own queue, avoiding one shared lock |
| Load balancing | Idle cores pull (or busy cores push) threads from others |
| Processor affinity | Prefer to keep a thread on the same core so its cache stays warm |
- Waiting time is turnaround minus burst, not "start time minus arrival" (that is response time, and they differ for preemptive algorithms).
- In SJF, only jobs that have already arrived can be chosen.
- State your Round Robin tie-break convention; different textbooks put new arrivals before or after the preempted job.
- The CPU may be idle if no job has arrived yet; leave a gap in the Gantt chart.
- Preemptive vs non-preemptive? Preemptive scheduling can stop a running thread (timer, higher-priority arrival); non-preemptive waits until it blocks or finishes.
- Which algorithm gives minimum average waiting time? SJF among non-preemptive algorithms, SRTF overall, but both need burst lengths and can starve long jobs.
- What is the convoy effect? In FCFS, many short jobs wait behind one long job, lowering utilisation and raising average wait.
- How do you prevent starvation in priority scheduling? Aging: gradually raise the priority of waiting processes.
- What happens if the RR quantum is very large? Very small? Large: it becomes FCFS. Small: context-switch overhead dominates.
- How does MLFQ estimate burst length? By behaviour: jobs using whole quanta are demoted; jobs that block early stay high. Periodic boosts prevent starvation.
- Turnaround = completion − arrival; waiting = turnaround − burst; response = first run − arrival.
- SJF/SRTF minimise average waiting but need burst knowledge; RR gives good response and fairness.
- Real schedulers (MLFQ, CFS/EEVDF) approximate these goals without knowing the future.
- Computer Architecture Overview
- Fundamentals: CPU, Memory and Instructions
- Pipelining
- Branches and Remedies
- Instruction-Level Parallelism
- Memory and Ordering
- Caches and Coherence
- Multicore
- Multithreading in Hardware
- SIMD and GPUs
- Glossary and Summary
- Hexagon Overview and Processor Properties
- ISA Fundamentals: Packets, Slots and Threads
- Registers
- Instruction Encoding and Mnemonics
- Data, Memory and Control Instructions
- Floating Point, HVX and Alignment
- Caches, MMU and Glossary
- Operating Systems Overview
- Processes
- Threads
- CPU Scheduling
- Synchronization
- Deadlock
- Memory Management
- Virtual Memory
- Files, Storage and I/O
- Kernel and System Calls
- Interview Q&A and Glossary
- C++ for LLVM Development: Overview
- C++ Basics
- Classes and RAII
- Ownership and Move Semantics
- Templates and Lambdas
- LLVM Data Structures (ADT)
- LLVM-Style RTTI: isa, cast, dyn_cast
- Errors, Output and Assertions
- Iterators and Ranges
- Building, Debugging and Exercises
- LLVM IR Overview
- Structure: Modules, Functions, Blocks and Values
- Type System
- Arithmetic, Bitwise and Cast Instructions
- Compare and Select
- Memory: alloca, load, store and getelementptr
- Control Flow: br, switch, ret and call
- SSA and Phi
- Control Flow Graph and Loops
- Dominance, Dominator Tree and Dominance Frontier
- Data-flow Analysis
- Writing an IR Pass
- Common Passes
- Exercises, Tooling and Glossary
- SelectionDAG Overview
- Pipeline, Phases and Traversal Orders
- Core Data Structures
- DAG Construction
- DAG Combiner
- Legalization
- Type Legalization
- Operation and Vector Legalization
- Instruction Selection
- TableGen Pattern Language
- Matcher Interpreter and Folding
- AArch64 Instruction Selection
- Scheduling and MIR Emission
- PHI Node Resolution
- AArch64 Walkthroughs
- Arithmetic and Data Movement
- Memory Instructions
- Control Flow and Calls
- End-to-End Example
- Tooling, Debugging and Extending
- Selector Comparison and Glossary
- Assignments: Build the Toy Backend
- Stage 1: Build Setup
- Stage 2: Target Registration
- Stage 3: TableGen Skeleton
- Stage 4: MC Layer for Assembly Output
- Stage 5: TargetMachine and Subtarget
- Stage 6: TargetLowering, Arguments and Returns
- Stage 7: Instruction Selection and the First Function
- Stage 8: Registers, Copies and Spills
- Stage 9: Frame Lowering
- Stage 10: Memory, Globals and Control Flow
- Stage 11: Calls
- Stage 12: Scheduling Model
- Stage 13: Object Files
- Stage 14: Capstone, a Complete Toy Backend
- Target Bring-up Overview
- Directory Layout, CMake and Registration
- The Target .td File
- TargetMachine and Subtarget
- TargetLowering Setup
- Calling Conventions
- Instructions and Instruction Selection
- Registers and Allocation Hooks
- Frame Lowering
- AsmPrinter and the MC Layer
- Scheduling
- A Minimal Toy Target
- Bring-up Checklist and AArch64 File Map
- Tooling and Glossary
- Calling Conventions Overview
- The CallingConv.td Language
- CCState and CCValAssign
- LowerFormalArguments
- LowerCall
- LowerReturn and CanLowerReturn
- Varargs, byval, sret and swifterror
- Tail Calls and Sibling Calls
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- Frame Lowering Overview
- MachineFrameInfo
- TargetFrameLowering Hooks
- The PEI Pass
- Callee-Saved Registers and Stack Layout
- Frame Index Elimination and the Register Scavenger
- Shrink Wrapping
- CFI and Unwind Information
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- MC Layer Overview
- Core Data Structures
- Streamers
- Assembler and Layout
- Fixups and Relocations
- Writing an MC Layer for a Custom Backend
- MCAsmInfo and the Instruction Printer
- Code Emitter
- AsmBackend and Object Writer
- Assembly Parser and Disassembler
- Bring-up Checklist and Common Failures
- Tooling and Glossary
- Register Allocation Overview
- The Register Allocation Pipeline
- Registers, Virtual Registers and Register Classes
- Liveness: Slot Indexes and Live Intervals
- Preparing Code for Allocation
- PHI Elimination and Two-Address Lowering
- Register Coalescer
- Allocation Framework
- The Register Allocators
- Fast Register Allocator
- Basic Register Allocator
- Greedy Register Allocator
- PBQP Register Allocator
- Spilling and Splitting
- Spill Weights and Copy Hints
- The Inline Spiller
- Live Range Splitting
- Rewriting and Post-RA Passes
- Writing Register Allocation Support for a Custom Backend
- Register Definitions in TableGen
- TargetRegisterInfo Hooks
- TargetInstrInfo Hooks
- Pass Pipeline Hooks
- Bring-up Checklist and Common Failures
- AArch64 Walkthroughs
- Tooling and Debugging
- Glossary and Where Do I Look