Operating Systems 📂 Scheduling Algorithm · 5 of 5 55 min read

Round-Robin Scheduling Algorithm

Master Round-Robin CPU scheduling from Galvin's Operating System Concepts. This tutorial covers the FIFO circular queue, time quantum trade-offs, and three fully worked numericals with step-by-step traces and animated SVG Gantt charts — including a same-arrival case, staggered arrivals, and a comparison of small vs large quantum. Includes context-switch overhead analysis, Python simulator code, real-world uses in Linux, Nginx, and 5G, and Galvin's 80% burst rule for choosing q.

Section 01

The Story That Explains Round-Robin

The Kindergarten Swing Rule
Picture a kindergarten with one swing and twenty children who all want to use it. Left to their own devices, the biggest kid would ride forever and the smallest would cry all recess. So the teacher enforces a simple rule: each child gets exactly 2 minutes on the swing, then must step off. If they still want more, they rejoin the back of the queue and wait their turn again.

No child is favoured. No child is starved. Everyone gets a fair, predictable slice. Yes, it's slower than letting one child ride until they're done — but nobody cries, and the system feels responsive to every child.

That, in one image, is Round-Robin Scheduling. Swap "children" for "processes" and "2 minutes on the swing" for a time quantum, and you have the algorithm that powers every timesharing operating system on Earth.

Round-Robin (RR) is the CPU scheduling algorithm designed specifically for time-sharing systems. It is essentially preemptive FCFS with a time limit. Each process gets a fixed slice of CPU time called the time quantum (or time slice). When the quantum expires, the process is preempted and moved to the tail of the ready queue, and the next process is dispatched.

💡
The Core Definition

Round-Robin Scheduling allocates CPU to each ready process in circular order for a fixed time quantum q. If a process's CPU burst ≤ q, it finishes and leaves. Otherwise, after q units it is preempted by a timer interrupt and placed at the tail of the ready queue. No priorities. No favouritism. Pure fair-share.


Section 02

Why Round-Robin Exists — The Timesharing Problem

Before RR, systems used FCFS (First-Come-First-Served). A single long-running job could hog the CPU for hours while everyone else waited. As soon as multiple users had to share one computer interactively, this became unbearable. RR was invented to make every user feel like they had the computer to themselves.

🚫 Before RR — Pure FCFS
TimeWhat User Sees
0 sJob A starts a 10-min computation
1 sUser B types a command → ignored
2 sUser C tries to save a file → frozen
...Everyone waits 10 minutes for A
600 sFinally A finishes, B runs, then C
✅ After RR — q = 100ms
TimeWhat User Sees
0 msJob A gets 100ms
100 msUser B's command runs in 100ms
200 msUser C's save runs in 100ms
300 msBack to A, then rotate again
...Every user feels <0.3s response
🏆
Galvin's Key Insight

Round-Robin trades throughput for responsiveness. No single process finishes faster than in FCFS, but every process gets to start quickly. This is why RR is the foundation of every interactive operating system since UNIX.


Section 03

Key Terms & The Time Quantum

📋 Vocabulary for Every RR Numerical
q
Time Quantum — the fixed CPU slice each process receives. Usually 10–100 ms in real systems, small integers (2, 4) in textbook problems.
AT
Arrival Time — when the process enters the ready queue.
BT
Burst Time — total CPU time needed. Under RR it is served in chunks of size q.
CT
Completion Time — when the process's last quantum ends and it exits.
TAT
Turnaround Time = CT − AT.
WT
Waiting Time = TAT − BT. Under RR this includes time waiting between quanta, not just before first run.
RT
Response Time = first CPU dispatch − AT. RR keeps this small — its main strength.
CS
Context Switch — the OS overhead of saving one process's state and loading another's. Usually ignored in numericals unless the problem states otherwise.
Turnaround Time
TAT = CT − AT
Total wall-clock time from arrival to completion, including waiting between quanta.
Waiting Time
WT = TAT − BT
Sum of all intervals the process spent in ready queue but not on CPU.

Section 04

The Ready Queue — A Circular FIFO

The ready queue in Round-Robin is a FIFO circular queue. The scheduler picks from the head, and preempted or newly-arrived processes go to the tail. Understanding this ordering is the single most common source of exam mistakes.

Ready Queue Life Cycle in Round-Robin
The Ready Queue in Motion CPU runs for quantum q HEAD (dispatch) TAIL (append) P1 P2 P3 P4 dispatch quantum expired Watch: head process moves left into CPU; when q expires, it goes to tail. Repeat forever.
⚠️
Tie-Break Rule at the Same Instant

If a running process's quantum ends at the same time a new process arrives, most textbooks (Galvin included) treat the new arrival as entering the queue first, then the preempted process is appended after it. Get this rule wrong and your entire Gantt chart shifts. State the assumption in exam solutions.


Section 05

Numerical 1 — Basic Round-Robin, Same Arrival

We'll start with the simplest case: all processes arrive at t=0. Time quantum q = 2.

ProcessArrival TimeBurst Time
P105
P203
P308
P406

Step-by-Step Queue Evolution (q = 2)

⏱️ Round-Robin Trace with Ready Queue Snapshot
t=0
All arrive together. Queue = [P1, P2, P3, P4]. Dispatch P1. BTrem(P1)=5.
t=0→2
P1 runs 2 units. Quantum expires. BTrem(P1)=3. P1 goes to tail. Queue = [P2, P3, P4, P1].
t=2→4
P2 runs 2 units. BTrem(P2)=1. Queue = [P3, P4, P1, P2].
t=4→6
P3 runs 2 units. BTrem(P3)=6. Queue = [P4, P1, P2, P3].
t=6→8
P4 runs 2 units. BTrem(P4)=4. Queue = [P1, P2, P3, P4].
t=8→10
P1 runs 2 units. BTrem(P1)=1. Queue = [P2, P3, P4, P1].
t=10→11
P2 needs only 1 unit — runs, completes at t=11. Queue = [P3, P4, P1].
t=11→13
P3 runs 2 units. BTrem(P3)=4. Queue = [P4, P1, P3].
t=13→15
P4 runs 2 units. BTrem(P4)=2. Queue = [P1, P3, P4].
t=15→16
P1 has only 1 unit left — runs, completes at t=16. Queue = [P3, P4].
t=16→18
P3 runs 2 units. BTrem(P3)=2. Queue = [P4, P3].
t=18→20
P4 runs its last 2 units. P4 completes at t=20. Queue = [P3].
t=20→22
P3 runs its last 2 units. P3 completes at t=22. Queue empty. Done.

Animated Gantt Chart (q = 2)

Round-Robin Execution — Same Arrival, q = 2
Round-Robin — Blocks Appear in Rotation Order P1 P2 P3 P4 P1 P2 P3 P4 P1 P3 P4 P3 0 2 4 6 8 10 11 13 15 16 18 20 22 P1 BT=5 P2 BT=3 P3 BT=8 P4 BT=6

Final Metrics Table

ProcessATBTCTTAT = CT − ATWT = TAT − BT
P105161611
P20311118
P308222214
P406202014
📈
Averages

Avg TAT = (16 + 11 + 22 + 20) / 4 = 69 / 4 = 17.25 ms
Avg WT = (11 + 8 + 14 + 14) / 4 = 47 / 4 = 11.75 ms


Section 06

Numerical 2 — Different Arrival Times (q = 2)

Now the tricky case that trips up students: processes arrive at different times. We must decide whether new arrivals or preempted processes go into the queue first. Rule: new arrival is enqueued before the preempted process at the same instant.

ProcessArrival TimeBurst Time
P104
P215
P322
P441
P562
⏱️ Detailed RR Trace with Arrival Interleaving (q=2)
t=0
P1 arrives. Queue = [P1]. Dispatch P1. BTrem(P1)=4.
t=1
P2 arrives → queue = [P2]. (P1 still running.)
t=2
P3 arrives → queue = [P2, P3]. P1's quantum ends. P1's BTrem=2 → P1 goes to tail. Queue = [P2, P3, P1]. Dispatch P2.
t=4
P4 arrives → append. P2 quantum ends. BTrem(P2)=3. Order: append P4 first (new arrival wins), then P2. Queue = [P3, P1, P4, P2]. Dispatch P3.
t=6
P5 arrives → append. P3 quantum ends. BTrem(P3)=0 → P3 completes at t=6! No re-enqueue. Then append P5. Queue = [P1, P4, P2, P5]. Dispatch P1.
t=8
P1 quantum ends. BTrem(P1)=0 → P1 completes at t=8. Queue = [P4, P2, P5]. Dispatch P4.
t=9
P4 needs only 1 unit → P4 completes at t=9. Queue = [P2, P5]. Dispatch P2.
t=11
P2 quantum ends. BTrem(P2)=1. Queue = [P5, P2]. Dispatch P5.
t=13
P5 quantum ends. BTrem(P5)=0 → P5 completes at t=13. Queue = [P2]. Dispatch P2.
t=14
P2 needs only 1 unit → P2 completes at t=14. Queue empty. Done.

Animated Gantt Chart with Arrival Markers

Round-Robin with Staggered Arrivals — q = 2
Round-Robin with Different Arrivals — q = 2 P1 P2 P3 P4 P5 P1 P2 P3 P1 P4 P2 P5 P2 0 2 4 6 8 9 11 13 14 P1 P2 P3 P4 P5 Order: P1 → P2 → P3 → P1 → P4 → P2 → P5 → P2

Final Table

ProcessATBTCTTATWT
P104884
P21514138
P322642
P441954
P5621375
📈
Averages

Avg TAT = (8 + 13 + 4 + 5 + 7) / 5 = 37 / 5 = 7.4 ms
Avg WT = (4 + 8 + 2 + 4 + 5) / 5 = 23 / 5 = 4.6 ms


Section 07

The Time Quantum — Small vs Large

The single most important design decision in Round-Robin is the value of the time quantum q. Get it wrong and RR degenerates into something worse than what it replaced.

🔫
Very Small q (e.g. 1 ms)
Processor Sharing Model
Every process feels like it has its own dedicated slow CPU. Excellent response time. But context switch overhead dominates — if a switch costs 0.1ms and quantum is 1ms, 10% of CPU is wasted on switching. Throughput collapses.
🛠️
Ideal q (10–100 ms)
Galvin's Rule of Thumb
Choose q so that 80% of CPU bursts are shorter than q. This lets most processes complete within a single quantum (no rotation cost), while still preempting the CPU-bound giants. This is the sweet spot for interactive systems.
🐌
Very Large q (∞)
Degenerates to FCFS
If q is larger than the longest burst, no preemption ever happens. Round-Robin becomes First-Come-First-Served. Response time becomes terrible for short jobs stuck behind long ones. You've lost RR's core benefit.

Numerical 3 — Same Workload, Two Different Quanta

Let's see the effect of quantum choice on the same workload. Processes: P1 (AT=0, BT=6), P2 (AT=0, BT=3), P3 (AT=0, BT=1), P4 (AT=0, BT=7).

🔫 q = 1 (tiny)
ProcessCTTATWT
P115159
P2996
P3332
P4171710
Avg11.06.75
🐌 q = 4 (large)
ProcessCTTATWT
P115159
P2774
P3887
P4171710
Avg11.757.5
📈
The Insight

Same processes, same total work — but average waiting time changed. Small q gives better response time for short processes (P3 finished at t=3 with q=1 versus t=8 with q=4). But small q means more context switches — the overhead in real systems can dominate. This is why real operating systems tune q carefully, typically matching it to typical burst distribution.


Section 08

Context Switch Overhead — The Hidden Cost

Textbook numericals usually ignore context switching. Real systems can't. A context switch requires saving all CPU registers, program counter, memory map pointers, and cache invalidation. On modern hardware this costs roughly 1–10 microseconds per switch.

CPU Utilisation vs Time Quantum
Effect of Time Quantum on CPU Utilisation Assuming context switch cost = 1 unit 0% 25% 50% 75% 100% 1 2 4 8 16 32 64 Time Quantum (units) CPU Utilisation Too small (switch overhead) Sweet spot (balanced) Too large (FCFS-like)
⚠️
CPU Utilisation Formula (Simplified)

If context switch takes s time units and quantum is q units, then useful CPU utilisation is U = q / (q + s). For q=1, s=1 → U = 50%. For q=10, s=1 → U = 91%. For q=100, s=1 → U = 99%. This is why real quanta are ~100× the context-switch cost.


Section 09

Turnaround Time vs Quantum — The Rule of 80%

Galvin's Recommendation: q should cover ~80% of CPU bursts
Avg Turnaround Time as a Function of Quantum Time Quantum Avg TAT 80% burst boundary optimal q Too small — many switches → FCFS Rule: choose q so that ~80% of CPU bursts finish within a single quantum

Section 10

Python Implementation

Complete Round-Robin Simulator

# Round-Robin Scheduling — event-driven simulator
# Convention: new arrival enqueued BEFORE the preempted process at the same instant

from collections import deque

def round_robin(processes, quantum):
    # processes: list of dicts { 'pid', 'at', 'bt' }
    n         = len(processes)
    remaining = {p['pid']: p['bt'] for p in processes}
    completed = {}
    ready     = deque()

    # Sort processes by arrival time
    procs = sorted(processes, key=lambda p: p['at'])
    i     = 0
    t     = procs[0]['at']

    # Enqueue processes that have arrived at time t
    while i < n and procs[i]['at'] <= t:
        ready.append(procs[i])
        i += 1

    while ready:
        curr = ready.popleft()
        run  = min(quantum, remaining[curr['pid']])
        start_t = t
        t += run
        remaining[curr['pid']] -= run

        # CRITICAL ORDERING:
        # First, enqueue all NEW arrivals that came in during (start_t, t]
        while i < n and procs[i]['at'] <= t:
            ready.append(procs[i])
            i += 1

        # Then, if the current process still has work, put it at the tail
        if remaining[curr['pid']] > 0:
            ready.append(curr)
        else:
            completed[curr['pid']] = {
                'ct':  t,
                'tat': t - curr['at'],
                'wt':  (t - curr['at']) - curr['bt'],
            }

        # If queue is empty but processes remain, jump to next arrival
        if not ready and i < n:
            t = procs[i]['at']
            while i < n and procs[i]['at'] <= t:
                ready.append(procs[i])
                i += 1

    return completed


# Example — Numerical 2
procs = [
    {'pid': 'P1', 'at': 0, 'bt': 4},
    {'pid': 'P2', 'at': 1, 'bt': 5},
    {'pid': 'P3', 'at': 2, 'bt': 2},
    {'pid': 'P4', 'at': 4, 'bt': 1},
    {'pid': 'P5', 'at': 6, 'bt': 2},
]

result = round_robin(procs, quantum=2)

print("PID  CT  TAT  WT")
for pid in sorted(result):
    m = result[pid]
    print(f"{pid:3} {m['ct']:3} {m['tat']:4} {m['wt']:3}")

avg_tat = sum(m['tat'] for m in result.values()) / len(result)
avg_wt  = sum(m['wt']  for m in result.values()) / len(result)
print(f"\nAvg TAT = {avg_tat:.2f}, Avg WT = {avg_wt:.2f}")
OUTPUT
PID CT TAT WT P1 8 8 4 P2 14 13 8 P3 6 4 2 P4 9 5 4 P5 13 7 5 Avg TAT = 7.40, Avg WT = 4.60

Section 11

Round-Robin vs Other Scheduling Algorithms

Feature Round Robin FCFS SJF Priority
Selection Rule Head of FIFO queue First arrived Shortest burst Highest priority
Preemption Yes (timer) No Either variant Either variant
Starvation Never Never Yes (long jobs) Yes (fix with aging)
Response Time Best (with small q) Worst Good for short Good for high-priority
Throughput Reduced by switches Highest High Depends
Fairness Maximum (equal share) Only in arrival order Unfair to long jobs Unfair to low priority
Ideal Use Case Timesharing / interactive Batch processing Batch with known bursts Real-time systems
🔑
Special Case Insight

When quantum q → ∞, Round-Robin becomes FCFS. When quantum q → 0, RR approaches the theoretical "processor-sharing" model where all n processes appear to run at 1/n speed simultaneously. Every real system chooses q somewhere between these two extremes.


Section 12

Advantages & Disadvantages

No Starvation
Advantage
Every process is guaranteed to get the CPU within (n−1)·q time. Perfect fairness. This is the single strongest argument for RR in interactive systems.
Great Response Time
Advantage
New arrivals get the CPU quickly — worst case just (n−1)·q wait. Interactive users feel the system is responsive even under heavy load.
Simple & Predictable
Advantage
No priority calculations, no burst prediction. A queue and a timer are all you need. Analysis and debugging are straightforward.
Context-Switch Overhead
Disadvantage
Every quantum expiry costs a switch. With small q, overhead can consume most of the CPU. Choosing q incorrectly can destroy performance.
Higher Average Turnaround
Disadvantage
RR usually has worse average TAT than SJF. Short processes must wait through several rotations before completing, whereas SJF would let them finish immediately.
Ignores Priorities
Disadvantage
A critical kernel task is treated exactly like a background wallpaper task. Pure RR is unsuitable for real-time systems — it needs to be combined with a priority scheme (Multilevel Queue).

Section 13

Real-World Applications

💻
UNIX/Linux Timesharing
Traditional UNIX used RR within each priority level. Modern Linux CFS is a "virtual runtime" refinement, but the core fair-share idea is Round-Robin.
/proc/sys/kernel/sched_*
🌐
Network Packet Scheduling
Weighted Round-Robin (WRR) and Deficit Round-Robin (DRR) are used by routers to give fair bandwidth to multiple flows. Every flow gets its "quantum" of packets sent.
Cisco QoS, Linux tc
🎪
Load Balancing
Nginx and HAProxy distribute incoming HTTP requests to backend servers in Round-Robin order. Simple, no state needed, guarantees each backend gets similar traffic.
nginx upstream, DNS round-robin
🖥️
Windows Thread Scheduling
Within a priority band, Windows uses RR to time-share among threads. Quantum is typically 20-120ms depending on version and workstation/server config.
Multilevel Feedback Queue base
⚙️
Multi-Threaded GPU Warps
NVIDIA GPUs schedule warps (groups of 32 threads) in round-robin fashion on each SM to hide memory latency. Every warp gets a chance while others wait for data.
Warp scheduler, SM
📡
Cellular Base Stations
4G/5G base stations use RR-like schedulers to allocate radio time slots fairly among connected devices, ensuring no single user monopolises the shared spectrum.
LTE/NR MAC scheduler

Section 14

Common Exam Traps & Pitfalls

🚩
Trap 1 — Arrival vs Preemption Order

When a process's quantum expires at the same instant another arrives, put the new arrival first, then the preempted process. Always state this convention explicitly. Different textbooks sometimes flip it.

🚩
Trap 2 — Completing Mid-Quantum

If a process's remaining burst is less than q, it runs only for that remaining time and completes — the CPU is not idle for the rest of the quantum. The next process starts immediately.

🚩
Trap 3 — CPU Idle Handling

If the ready queue is empty and no process has arrived yet, the CPU sits idle. Fast-forward time to the next arrival — do not include this idle time in any process's waiting time.

🚩
Trap 4 — Do Not Sort by Burst

Round-Robin does not care about burst length. Do not "optimise" by picking shorter jobs first — that would be SJF. RR is strictly FIFO in the queue.


Section 15

Golden Rules — Round-Robin Scheduling

🎖 Galvin's Non-Negotiable Rules
1
Ready queue is FIFO circular. Dispatch from the head. Preempted or newly arrived processes always append to the tail. No reordering allowed. Ever.
2
Time quantum is fixed and universal. Every process gets the same slice. There are no per-process quanta in vanilla Round-Robin (that's Weighted RR — a different algorithm).
3
At the same instant, new arrivals enter the queue before preempted processes. Always state this convention in your solution. It changes the Gantt chart.
4
A process that finishes mid-quantum releases the CPU immediately. The remaining time is not wasted — the next process starts right away.
5
Choose q ≈ 80% burst boundary. The optimal quantum lets ~80% of CPU bursts finish within a single slice. Too small → context switches dominate. Too large → RR becomes FCFS.
6
Round-Robin never starves anyone. Every process is guaranteed to get CPU within (n−1)·q time. This is RR's core selling point; do not sacrifice it lightly.
7
Formulas are the same as every other algorithm: TAT = CT − AT and WT = TAT − BT. What changes is the trace, not the arithmetic.
8
Pure Round-Robin ignores priority. In real systems (Linux, Windows), RR is used within each priority class of a Multilevel Queue — combining fairness inside a class with priority between classes.
You have completed Scheduling Algorithm. View all sections →