SkillGridLearn computer science by doing

CPU scheduling

How the OS decides who runs next, and why that choice changes both average waiting time and fairness.

14 min · 42 XP

There is always more work than CPU. The scheduler picks one ready process at a time, and that choice decides who waits. Different goals — throughput, latency, fairness — lead to different algorithms.

CPU scheduler

A long job arrives first. Watch how everything behind it waits.

Processes
ProcessArrivalBurstStateUsed
P106waiting—
P214waiting—
P322waiting—
P431waiting—
Ready queue
  1. P1

P1 arrives with a burst of 6ms

Avg waiting time
0
Avg turnaround time
0
Total time
0
Compare algorithms
AlgorithmAvg waiting timeAvg turnaround timeTotal time
First-Come, First-Served5.58.7513
Shortest Job First47.2513
Round-Robin5.75913

Waiting time is how long a process sat ready without running. Turnaround time is from arrival to completion. These two numbers are what scheduling algorithms are actually judged on.

Round-Robin gives each process a fixed slice (a quantum) and rotates. No process waits forever, which is why it feels responsive — but short quanta mean more context switches, and those cost real time.

Ready queueCPUP1 runs (quantum = 2)quantum expired, P1 to the backP2 runs (quantum = 2)quantum expired, P2 to the backP3 runs (quantum = 2)P3 finishedP1 again, the queue keeps rotating
# Правило, которое стоит запомнить:
#
#   waiting time    = (момент завершения - приход) - burst
#   turnaround time =  момент завершения - приход
#
# Пример из набора «convoy» (P1=6, P2=4, P3=2, P4=1):
#
#   FCFS: P1[0..6] P2[6..10] P3[10..12] P4[12..13]
#         среднее ожидание = (0 + 5 + 8 + 9) / 4 = 5.5
#
#   SJF : P1[0..6] P4[6..7] P3[7..9] P2[9..13]
#         среднее ожидание = (0 + 3 + 5 + 8) / 4 = 4.0
#
# SJF выигрывает, потому что короткие работы успевают
# пройти раньше, а не стоят за длинной. Это и есть convoy effect.

Practice

  1. Which algorithm can starve a long job indefinitely if short jobs keep arriving?

    Hints
    • Think about which job keeps getting overtaken by shorter arrivals.
    • One of these algorithms never lets a new short job jump the queue.

    12 XP

  2. Using the simulator below, compare FCFS and SJF on the same process set. Which gives a lower average waiting time, and why?

    Hints
    • Run both and compare the average waiting time the simulator prints.
    • Ask whether a long job is delaying the short ones behind it.

    18 XP

  3. Put the scheduling decisions in the order Round-Robin makes them for P1(4ms), P2(2ms) with a 2ms quantum.

    Hints
    • Each process gets the quantum before being preempted.
    • A process that finishes early leaves the queue.

    15 XP