Step 04

CPU Scheduling

Many processes are ready but there is only one CPU. The scheduler decides who runs next. Change the numbers below and see instantly how the Gantt chart and the average waiting time change.

Process Scheduling in Operating Systems

A computer runs many programs at once — the browser, the music player, the compiler, dozens of background services — yet it usually has only one (or a few) CPUs. Process scheduling is the activity of the operating system that decides which process owns the CPU at any given moment, and for how long. The part of the OS that makes this decision is called the scheduler, and the code that performs the actual switch is the dispatcher.

Good scheduling has three goals: keep the CPU busy (high utilisation), finish many jobs quickly (high throughput), and keep users happy by responding fast (low response time) and not making any single job wait too long (low turnaround time). These goals often conflict — favouring short jobs raises throughput but can starve a long job — so every scheduling algorithm is a different trade-off.

Real-world analogy: A railway control room

Think of the CPU as a single railway track and processes as trains waiting to use it. The scheduler is the controller who picks which train goes next, the dispatcher is the switch operator that actually moves the points, and the ready queue is the sidings where trains wait. Different controllers follow different rules — some strict first-come-first-served, some let short express trains jump the queue — and each rule changes how long the average train waits.
Types of Process Schedulers

Operating systems mainly use three types of schedulers to manage process execution and memory efficiently. Each one moves a process from one queue to another:

SchedulerAlso calledMoves process…FrequencyMain goal
Long-termJob schedulerNew → Ready (admits a job from the pool on disk into memory)Rarely (seconds–minutes)Control the degree of multiprogramming
Short-termCPU schedulerReady → Running (selects which ready process gets the CPU next)Very often (milliseconds)Maximise CPU utilisation & responsiveness
Medium-termSwapperReady/Running ↔ Suspended (swaps processes out to disk and back)Occasionally (when memory is tight)Balance memory load, enable swapping

1. Long Term Scheduler (Job Scheduler)

The long term scheduler is responsible for selecting processes from the job pool (stored on disk) and loading them into the main memory (RAM). Once loaded, these processes move into the ready state.

Long term scheduler selecting jobs from the job pool on disk and loading them into main memory and the ready queue
  • Multiprogramming: Controls how many processes are present in memory at a time (degree of multiprogramming).
  • Selection criteria: Selects processes based on factors like priority, resource needs, or execution time.
  • Frequency: Invoked less frequently (every few seconds or minutes).
  • Speed: Slowest scheduler because it involves heavy disk operations.

2. Short Term Scheduler (CPU Scheduler)

The short term scheduler chooses a process from the ready queue and assigns it to the CPU for execution.

Short term scheduler selecting a process from the ready queue and the dispatcher performing context switches with the CPU
  • Algorithms: Works with scheduling algorithms like FCFS, SJF, and Round Robin.
  • Frequency: Runs very frequently (every few milliseconds).
  • Speed: Fastest scheduler because decisions must be made extremely quickly.
  • Dispatcher: Uses a dispatcher to physically switch the CPU between processes (saving state, loading state, transferring control). The time taken for this switch is called dispatch latency.

3. Medium Term Scheduler (Swapper)

The medium term scheduler manages memory by temporarily removing processes from RAM and storing them on disk. This process is called swapping.

Medium term scheduler swapping processes out of main memory to secondary storage and back in
  • Memory load: Reduces memory load by suspending some processes.
  • Performance: Helps improve overall system performance during heavy load.
  • Frequency: Invoked occasionally when memory is limited.
  • Speed: Speed is between long term and short term schedulers.

Together, the long-term scheduler controls entry into the system, the short-term scheduler controls entry into the CPU, and the medium-term scheduler can pull a process out to disk (suspend) and re-introduce it later.

   [Pool of jobs]            [Ready queue]            [CPU]
   on disk                  in memory                (Running)
      │                        ▲                        │
      │  long-term             │  short-term             │  time slice
      └─────── admit ──────────┘  schedule ─────────────┘  expires / block
                                    │                        │
                                    │      medium-term        │
                                    │   suspend ◀────────────┤
                                    │   resume  ──────▶      │
                                 [Suspended / swapped out]   │
                                      (on disk)              ▼
                                          [Terminated]
Scheduling queues & the context switch

Every process the OS knows about sits in one of several queues. The two queues you will keep meeting are the job queue (every process in the system) and the ready queue (processes in memory, waiting only for the CPU). Processes that are blocked on an I/O operation sit in the device queue for that device. The OS keeps a queue for each device, so I/O-bound and CPU-bound processes naturally separate.

When the short-term scheduler picks a new process, the dispatcher performs a context switch: it saves the running process's register values and program counter into its PCB, loads the next process's saved state from its PCB, and hands control to the next process. This switch is pure overhead — no useful work happens during it — so a good scheduler tries not to switch more often than necessary.

Degree of multiprogramming — number of processes competing for the CPU at once
CPU-bound process — spends most of its time computing
I/O-bound process — spends most of its time waiting on I/O devices
Context-switch time — overhead paid on every switch; typically 1–10 μs
Preemptive vs non-preemptive scheduling

Non-preemptive

Once a process gets the CPU, it keeps it until it finishes or yields (e.g. for I/O). No other process can force it off. FCFS and non-preemptive SJF/Priority work this way. Simple and predictable, but a long job can hold everyone up.

Preemptive

The OS can interrupt the running process — when its time slice ends, or when a higher priority process arrives — and give the CPU to someone else. Round Robin, SRTF and preemptive Priority work this way. Better responsiveness, but more context-switch overhead.

Vocabulary you need first
Arrival Time (AT) — when the process enters the ready queue
Burst Time (BT) — CPU time the process needs to finish
Completion Time (CT) — the instant the process finishes
Turnaround Time (TAT) — CT − AT: total time spent in the system
Waiting Time (WT) — TAT − BT: time spent waiting in the ready queue
Response Time (RT) — first CPU allocation − AT
Throughput — number of processes completed per unit time
Starvation — a process waiting forever because others keep jumping ahead

Real-world analogy: One chef, many customers

The CPU is a single chef. FCFS serves customers strictly in the order they arrived. SJF serves the quickest order first (great for averages, but a big order may starve). Round Robin gives every customer a fixed few minutes of the chef's time in turn, so nobody feels ignored.

Interactive lab

CPU Scheduling Algorithms

Compare how each scheduling policy allocates CPU time, builds the Gantt chart, and affects process wait times.

Experiment: Scheduling simulator with live Gantt chart
ProcessArrival timeBurst timePriority

Average waiting time: 5.75 ms

Average turnaround time: 10.25 ms

Selected algorithm

FCFS (First Come First Served)

Non-preemptive

Gantt chart

P1
0
P2
5
P3
8
P4
1618
ProcessATBTCTTAT = CT − ATWT = TAT − BTRT
P10555 − 0 = 55 − 5 = 00
P21388 − 1 = 77 − 3 = 44
P3281616 − 2 = 1414 − 8 = 66
P4321818 − 3 = 1515 − 2 = 1313

Step-by-step trace

  1. t=0: P1 is selected (earliest arrival) and runs to completion.
  2. t=5: P1 finished. Completion time = 5.
  3. t=5: P2 is selected (earliest arrival) and runs to completion.
  4. t=8: P2 finished. Completion time = 8.
  5. t=8: P3 is selected (earliest arrival) and runs to completion.
  6. t=16: P3 finished. Completion time = 16.
  7. t=16: P4 is selected (earliest arrival) and runs to completion.
  8. t=18: P4 finished. Completion time = 18.
Comparing the algorithms
AlgorithmPreemptive?StrengthWeakness
FCFSNoSimplest, fair by arrival orderConvoy effect: a long job delays everyone
SJFNoMinimum average waiting timeNeeds burst time in advance; starvation of long jobs
SRTFYesEven better averages than SJFFrequent context switches; starvation
PriorityBothImportant jobs run firstLow-priority starvation (fix with ageing)
Round RobinYesFair, great response time for interactive usersToo small a quantum = high context-switch overhead
Try it: run the same table with FCFS, then SJF
Then set Round Robin quantum = 1 and compare
Quick quiz

1. Which algorithm gives the minimum average waiting time (non-preemptive)?

2. The convoy effect is a problem of:

3. In Round Robin, what happens if the quantum becomes very large?

Practice problem

Processes: P1(AT 0, BT 4), P2(AT 1, BT 3), P3(AT 2, BT 1). Compute the average waiting time using FCFS. Then verify with the simulator above.