This post builds the Round Robin (RR) CPU scheduling algorithm from scratch in C++ and in plain C, then runs it on several workloads and prints a Gantt chart and a waiting-time table for each. Round Robin is the standard algorithm for time-sharing systems because it gives every process a fair, equal slice of CPU time. Each process runs for a fixed duration called the time quantum, is then preempted, and goes to the back of the ready queue.
It is a rewrite of the earlier version of this article. The old table of numbers was right, but its Gantt chart was not, it could not handle processes arriving at different times, and it printed no chart at all. Everything below was compiled and run, and every table and chart in the post is copied from a file in the companion repository.
Tested with. gcc / g++ 13.3.0 (Ubuntu 24.04),-std=c++17for C++ and-std=c11for C, compiled with-Wall -Wextraand no warnings. Regenerate every output file with scripts/run-all.sh. Last run: 26 November 2026.
Everyone gets a turn, but only a short one
Suppose five programs want the CPU at the same moment and one of them needs 29 time units while another needs only 3. If you run them in arrival order (First Come First Served), the 3-unit job may wait behind the 29-unit one. Round Robin avoids that: all processes sit in a circular queue, the CPU runs the front process for at most Q units, and if it is not finished it is interrupted and placed at the back. This repeats until every process completes.
- Time Quantum (Q) — The maximum CPU time a process gets per turn. A smaller Q improves response time but increases context-switch overhead. A very large Q degrades to FCFS behavior.
- Waiting Time (WT) — Total time the process spent waiting in the ready queue across all its turns, not including its own execution time. With arrival times:
WT = CT − AT − BT. - Turnaround Time (TT or TAT) — From arrival to completion:
TAT = CT − AT, which equalsWT + BT. (CT is completion time, AT arrival time, BT burst time.)
The diagram shows the whole algorithm: a FIFO queue feeding a CPU that holds each process for at most Q units, with exactly two exits — done, or back to the tail. Hold on to that shape; every program below is just this loop written down.
Going deeper: why a FIFO queue and not a sort
Unlike SJF or Priority scheduling, Round Robin never compares processes with each other. The only decision is “who is at the front”, which is why the data structure is a plain queue and why the algorithm cannot starve anyone: a process waits at most the other processes’ slices (n−1 of them) before it runs again. Compare with SJF, where a long job can wait indefinitely behind a stream of short ones.
Work one example by hand before reading any code
Take five processes, all arriving at time 0, with burst times 10, 29, 3, 7 and 12, and a quantum of 10. At each step, take the front of the queue, run it for min(Q, remaining), and either finish it or append it to the back.
| Start time | Queue before | Runs | Slice | Remaining after | Result |
|---|---|---|---|---|---|
| 0 | P1 P2 P3 P4 P5 | P1 | 0–10 | 0 | finishes at 10 |
| 10 | P2 P3 P4 P5 | P2 | 10–20 | 19 | back to tail |
| 20 | P3 P4 P5 P2 | P3 | 20–23 | 0 | finishes at 23 |
| 23 | P4 P5 P2 | P4 | 23–30 | 0 | finishes at 30 |
| 30 | P5 P2 | P5 | 30–40 | 2 | back to tail |
| 40 | P2 P5 | P2 | 40–50 | 9 | back to tail |
| 50 | P5 P2 | P5 | 50–52 | 0 | finishes at 52 |
| 52 | P2 | P2 | 52–61 | 0 | finishes at 61 |
Plotted on a time axis, those eight slices are the Gantt chart. This is the output of rr.cpp for this workload, in file output/01-rr-legacy-5proc-q10.txt:
The chart is the trace table drawn to scale: the boxes follow the order of the “Runs” column, and the numbers underneath are the slice boundaries.
Round Robin, time quantum = 10
PID AT BT CT TAT WT
P1 0 10 10 10 0
P2 0 29 61 61 32
P3 0 3 23 23 20
P4 0 7 30 30 23
P5 0 12 52 52 40
Average waiting time : 23.00
Average turnaround time : 35.20
Gantt chart:
| P1 | P2 | P3 | P4 | P5 | P2 | P5 | P2 |
0 10 20 23 30 40 50 52 61
Correction to the earlier version of this post. The old Gantt chart listed P2 at 50–60 and 60–61 and described P5 as finishing “after the other processes finish”. That is not Round Robin: after P2’s turn at 40–50, P5 is next in the queue and runs 50–52, and only then does P2 get its final 9 units (52–61). The waiting-time table in the old post was correct; only the chart and the prose under it were wrong. I found it by drawing the chart from the real simulation instead of from the table.
Reading the table: P1 (BT 10) gets its whole burst in one turn, so WT = 0 and TAT = 10. P2 (BT 29) runs three times (10 + 10 + 9 units), waits 32 and finishes at 61. P3 (BT 3) finishes inside one quantum after waiting 20. P4 (BT 7) waits 23. P5 (BT 12) runs 10 units, waits, then runs its last 2 units and finishes at 52 with WT 40. Averages: WT = (0 + 32 + 20 + 23 + 40) / 5 = 23 and TAT = (10 + 61 + 23 + 30 + 52) / 5 = 35.2, matching the output above.
Going deeper: checking the arithmetic yourself
Total waiting is just total turnaround minus total burst time, divided by the number of processes. Total burst here is 10 + 29 + 3 + 7 + 12 = 61, which is also the CPU’s finish time because nothing ever idles when every process arrives at 0. The source of every number is in output/01-rr-legacy-5proc-q10.txt.
The smallest program that gets it right
The program reads n, then one line of arrival burst per process, then the quantum. It keeps a real ready queue, which makes the code look like the diagram. The full source is rr.cpp; open the accordion to read it here.
C++ source: rr.cpp (click to open)
// Round Robin (RR) CPU scheduling - preemptive, with arrival times and a Gantt chart.
// Input : n, then n lines of "arrival burst", then the time quantum Q.
// Rule : a process that arrives while another is running joins the ready queue BEFORE
// the preempted process is put back at the tail (the usual textbook convention).
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
struct Process {
int pid, at, bt, rem;
int ct = 0, tat = 0, wt = 0; // completion, turnaround, waiting
};
struct Slice { int pid, start, end; }; // pid = 0 means CPU idle
int main() {
int n, q;
cin >> n;
vector<Process> p(n);
for (int i = 0; i < n; i++) { p[i].pid = i + 1; cin >> p[i].at >> p[i].bt; p[i].rem = p[i].bt; }
cin >> q;
vector<int> order(n); // process indexes sorted by arrival, then pid
for (int i = 0; i < n; i++) order[i] = i;
stable_sort(order.begin(), order.end(), [&](int a, int b) { return p[a].at < p[b].at; });
queue<int> ready;
vector<Slice> gantt;
int time = 0, next = 0, finished = 0;
auto admit = [&]() { while (next < n && p[order[next]].at <= time) ready.push(order[next++]); };
while (finished < n) {
admit();
if (ready.empty()) { // nobody has arrived yet: CPU idles
int t = p[order[next]].at;
gantt.push_back({0, time, t});
time = t;
continue;
}
int i = ready.front(); ready.pop();
int run = min(q, p[i].rem);
if (!gantt.empty() && gantt.back().pid == p[i].pid && gantt.back().end == time)
gantt.back().end += run; // same process continues: extend its box
else
gantt.push_back({p[i].pid, time, time + run});
time += run;
p[i].rem -= run;
admit(); // arrivals during the slice go in first...
if (p[i].rem > 0) ready.push(i); // ...then the preempted process goes to the tail
else { p[i].ct = time; p[i].tat = p[i].ct - p[i].at; p[i].wt = p[i].tat - p[i].bt; finished++; }
}
cout << "Round Robin, time quantum = " << q << "\n\n";
cout << "PID\tAT\tBT\tCT\tTAT\tWT\n";
double sw = 0, st = 0;
for (auto& x : p) {
cout << "P" << x.pid << "\t" << x.at << "\t" << x.bt << "\t" << x.ct << "\t" << x.tat << "\t" << x.wt << "\n";
sw += x.wt; st += x.tat;
}
cout << fixed << setprecision(2);
cout << "\nAverage waiting time : " << sw / n << "\n";
cout << "Average turnaround time : " << st / n << "\n\nGantt chart:\n";
string top, nums;
for (auto& s : gantt) {
string label = (s.pid ? "P" + to_string(s.pid) : string("idle"));
if (nums.size() < top.size()) nums += string(top.size() - nums.size(), ' ');
nums += to_string(s.start);
top += "| " + label + " ";
}
top += "|";
if (nums.size() < top.size() - 1) nums += string(top.size() - 1 - nums.size(), ' ');
nums += to_string(gantt.back().end);
cout << top << "\n" << nums << "\n";
}
The same logic in plain C, with a circular array instead of std::queue, is rr.c. It prints byte-for-byte the same output as the C++ version on every sample input (output/09-c-vs-cpp.txt):
identical input/classic-q4.txt
identical input/idle-gap-q3.txt
identical input/large-quantum.txt
identical input/legacy-5proc-q10.txt
identical input/quantum-1.txt
identical input/staggered-q2.txt
C source: rr.c (click to open)
/* Round Robin (RR) CPU scheduling in plain C - same rules and same output as rr.cpp.
* Input : n, then n lines of "arrival burst", then the time quantum Q.
* The ready queue is a circular array; arrivals during a slice are enqueued before the
* preempted process goes back to the tail. */
#include <stdio.h>
#define MAXP 64
#define MAXS 1024
int main(void) {
int n, q;
int at[MAXP], bt[MAXP], rem[MAXP], ct[MAXP], tat[MAXP], wt[MAXP], admitted[MAXP] = {0};
int queue[MAXP + 1], head = 0, tail = 0; /* circular, one spare slot */
int gp[MAXS], gs[MAXS], ge[MAXS], g = 0; /* Gantt slices: pid (0 = idle), start, end */
int time = 0, finished = 0, i;
if (scanf("%d", &n) != 1 || n < 1 || n > MAXP) return 1;
for (i = 0; i < n; i++) { if (scanf("%d %d", &at[i], &bt[i]) != 2) return 1; rem[i] = bt[i]; }
if (scanf("%d", &q) != 1 || q < 1) return 1;
while (finished < n) {
/* admit every process that has arrived by 'time', in arrival order (ties: lower pid) */
for (;;) {
int best = -1;
for (i = 0; i < n; i++)
if (!admitted[i] && at[i] <= time && (best < 0 || at[i] < at[best])) best = i;
if (best < 0) break;
admitted[best] = 1; queue[tail] = best; tail = (tail + 1) % (MAXP + 1);
}
if (head == tail) { /* ready queue empty: CPU idles */
int t = -1;
for (i = 0; i < n; i++) if (!admitted[i] && (t < 0 || at[i] < t)) t = at[i];
gp[g] = 0; gs[g] = time; ge[g] = t; g++; time = t;
continue;
}
i = queue[head]; head = (head + 1) % (MAXP + 1);
int run = rem[i] < q ? rem[i] : q;
if (g > 0 && gp[g - 1] == i + 1 && ge[g - 1] == time) ge[g - 1] += run;
else { gp[g] = i + 1; gs[g] = time; ge[g] = time + run; g++; }
time += run; rem[i] -= run;
for (;;) { /* arrivals during the slice go in first */
int best = -1, j;
for (j = 0; j < n; j++)
if (!admitted[j] && at[j] <= time && (best < 0 || at[j] < at[best])) best = j;
if (best < 0) break;
admitted[best] = 1; queue[tail] = best; tail = (tail + 1) % (MAXP + 1);
}
if (rem[i] > 0) { queue[tail] = i; tail = (tail + 1) % (MAXP + 1); }
else { ct[i] = time; tat[i] = ct[i] - at[i]; wt[i] = tat[i] - bt[i]; finished++; }
}
printf("Round Robin, time quantum = %d\n\nPID\tAT\tBT\tCT\tTAT\tWT\n", q);
double sw = 0, st = 0;
for (i = 0; i < n; i++) {
printf("P%d\t%d\t%d\t%d\t%d\t%d\n", i + 1, at[i], bt[i], ct[i], tat[i], wt[i]);
sw += wt[i]; st += tat[i];
}
printf("\nAverage waiting time : %.2f\nAverage turnaround time : %.2f\n\nGantt chart:\n", sw / n, st / n);
{ /* top row of boxes, bottom row of boundary times, aligned by column */
char top[4096] = "", nums[4096] = "", lab[16];
int tl = 0, nl = 0, k;
for (k = 0; k < g; k++) {
if (gp[k]) snprintf(lab, sizeof lab, "P%d", gp[k]); else snprintf(lab, sizeof lab, "idle");
while (nl < tl) nums[nl++] = ' ';
nl += snprintf(nums + nl, sizeof nums - nl, "%d", gs[k]);
tl += snprintf(top + tl, sizeof top - tl, "| %s ", lab);
}
tl += snprintf(top + tl, sizeof top - tl, "|");
while (nl < tl - 1) nums[nl++] = ' ';
snprintf(nums + nl, sizeof nums - nl, "%d", ge[g - 1]);
printf("%s\n%s\n", top, nums);
}
return 0;
}
How the code works, step by step
- Ready queue.
queue<int> readyholds process indexes. Taking the front and, if work remains, pushing it back to the tail is the circular queue from the diagram. - Run for min(Q, remaining).
run = min(q, p[i].rem)is the whole preemption rule: a process runs a full quantum unless it needs less, and then it finishes. - Remaining vs original burst.
btkeeps the original burst for the table, whileremis decremented as the process runs. - Completion bookkeeping. When
remreaches 0 the code recordsct = time, thentat = ct - atandwt = tat - bt. No tick-by-tick waiting counter is needed. - Idle CPU. If the queue is empty but processes have not arrived yet, the clock jumps to the next arrival and the Gantt chart gets an
idlebox. - Merged boxes. If the same process runs twice in a row (it is alone in the queue), its two slices are drawn as one box.
- Going deeper: scripts/run-all.sh builds both programs and regenerates all output files; README.md lists the inputs.
When processes arrive late, one tie-break rule decides the queue
Real processes do not all arrive at time 0. Take four processes arriving at 0, 1, 2 and 4 with bursts 5, 4, 2 and 1, and Q = 2 (input/staggered-q2.txt). One question comes up immediately: P2 arrives at time 1, while P1 is still running. When P1’s slice ends at 2, P1 is not finished. Does P1 go to the back before P2 and P3, or after them?
The convention used here (and in most textbooks) is that processes that arrived during the slice enter the queue first, and the preempted process goes behind them. The trace shows the effect:
| Start time | Queue before | Runs | Slice | Queue after (arrivals first, then preempted) |
|---|---|---|---|---|
| 0 | P1 | P1 | 0–2 | P2 P3 P1 |
| 2 | P2 P3 P1 | P2 | 2–4 | P3 P1 P4 P2 |
| 4 | P3 P1 P4 P2 | P3 | 4–6 | P1 P4 P2 (P3 done, CT 6) |
| 6 | P1 P4 P2 | P1 | 6–8 | P4 P2 P1 |
| 8 | P4 P2 P1 | P4 | 8–9 | P2 P1 (P4 done, CT 9) |
| 9 | P2 P1 | P2 | 9–11 | P1 (P2 done, CT 11) |
| 11 | P1 | P1 | 11–12 | empty (P1 done, CT 12) |
The program output, from output/03-rr-staggered-q2.txt, agrees with the trace:
Round Robin, time quantum = 2
PID AT BT CT TAT WT
P1 0 5 12 12 7
P2 1 4 11 10 6
P3 2 2 6 4 2
P4 4 1 9 5 4
Average waiting time : 4.75
Average turnaround time : 7.75
Gantt chart:
| P1 | P2 | P3 | P1 | P4 | P2 | P1 |
0 2 4 6 8 9 11 12
Know which convention your textbook uses. The other possible rule (put the preempted process back first, then the new arrivals) can give a different queue order and therefore different waiting times for the same input. Exam answers are marked against the convention in your syllabus, so state the rule you are using when you write the dry run.
If nothing is ready, the CPU idles until the next arrival. Three processes arriving at 0, 10 and 11 with Q = 3 (input/idle-gap-q3.txt) show the idle box between times 4 and 10 (output/04-rr-idle-gap-q3.txt):
Round Robin, time quantum = 3
PID AT BT CT TAT WT
P1 0 4 4 4 0
P2 10 3 13 3 0
P3 11 2 15 4 2
Average waiting time : 0.67
Average turnaround time : 3.67
Gantt chart:
| P1 | idle | P2 | P3 |
0 4 10 13 15
Choosing the quantum: too small wastes the CPU, too large turns into FCFS
The quantum is the only tuning knob. To see its effect, the script ran the same five-process workload from earlier at eleven different quanta and recorded the average waiting time and the number of boxes in the Gantt chart (output/08-quantum-sweep.txt):
Q avg-WT avg-TAT gantt-boxes
1 25.00 37.20 45
2 25.40 37.60 24
3 25.00 37.20 17
5 24.60 36.80 12
7 24.20 36.40 9
10 23.00 35.20 8
12 22.20 34.40 6
15 24.00 36.20 6
20 27.00 39.20 6
29 28.00 40.20 5
40 28.00 40.20 5
Two things stand out. The number of Gantt boxes (a rough proxy for context switches) falls fast as Q grows, from 45 at Q=1 down to 5 at Q=29. But average waiting time is not monotonic: it is lowest at Q=12 and rises again, and from Q=29 (the longest burst) upward it is a constant 28.00, because no process is ever preempted and the order is simply arrival order — FCFS. Boxes undercount real switches slightly, because the program merges consecutive slices of the same process.
The classic textbook case shows the other side: three processes with bursts 24, 3 and 3 and Q = 4 (output/02-rr-classic-q4.txt) let the two short jobs finish at times 7 and 10 instead of waiting behind the 24-unit job:
Round Robin, time quantum = 4
PID AT BT CT TAT WT
P1 0 24 30 30 6
P2 0 3 7 7 4
P3 0 3 10 10 7
Average waiting time : 5.67
Average turnaround time : 15.67
Gantt chart:
| P1 | P2 | P3 | P1 |
0 4 7 10 30
With a quantum larger than every burst, four 8-unit processes simply run one after another (output/06-rr-large-quantum.txt):
Round Robin, time quantum = 100
PID AT BT CT TAT WT
P1 0 8 8 8 0
P2 0 8 16 16 8
P3 0 8 24 24 16
P4 0 8 32 32 24
Average waiting time : 12.00
Average turnaround time : 20.00
Gantt chart:
| P1 | P2 | P3 | P4 |
0 8 16 24 32
Context-switch cost is why Q cannot shrink to 1. Suppose a context switch costs 1 time unit (an assumed figure for illustration). With Q = 4 you spend 1 of every 5 units switching — 20% overhead. Real systems pick Q large enough that switching is a small fraction of each slice, but small enough that interactive programs respond quickly. A common rule of thumb is that most CPU bursts should be shorter than Q.
Going deeper: the quantum-1 trace and the response-time bound
With Q = 1 and bursts 6, 4, 2 (input/quantum-1.txt), the processes interleave one unit at a time (output/05-rr-quantum-1.txt):
Round Robin, time quantum = 1
PID AT BT CT TAT WT
P1 0 6 12 12 6
P2 0 4 10 10 6
P3 0 2 6 6 4
Average waiting time : 5.33
Average turnaround time : 9.33
Gantt chart:
| P1 | P2 | P3 | P1 | P2 | P3 | P1 | P2 | P1 | P2 | P1 |
0 1 2 3 4 5 6 7 8 9 10 12Because every process in the queue gets a turn before any process gets a second one, a process that has just arrived waits at most (n − 1) × Q units before its first run. This bound on response time is the main selling point of Round Robin for interactive systems.
What the earlier version got right, and where it stops
The original program had no queue. It stepped through time one unit at a time, rotated an index around the process array, and tracked waiting time with a clever subtraction: at the start of each turn it stored tick − Q × roundsAlreadyUsed. That works only when every process arrives at time 0, because it has no concept of arrival time. Within that limit it is correct: the script ran it against the new program on 500 random workloads with all arrivals at 0, and the waiting times never differed (output/10-legacy-vs-new.txt):
random workloads (all arrivals at 0, seed 2015): 500
waiting-time mismatches, legacy vs rr.cpp : 0
Here is a full session of the legacy program on the workload from the first section, with its prompts, the “Entered Data” echo (note the garbled header) and the same result table the earlier post showed (output/07-legacy-full-session.txt):
Enter No of Processes:
Enter Burst Time of Process 1:
Enter Burst Time of Process 2:
Enter Burst Time of Process 3:
Enter Burst Time of Process 4:
Enter Burst Time of Process 5:
Enter Time Quantum:
Entered Data
ProcesstBurst Time
1 10
2 29
3 3
4 7
5 12
Result of Round Robin Scheduling
PNo BT WT TT
1 10 0 10
2 29 32 61
3 3 20 23
4 7 23 30
5 12 40 52
Average Waiting Time : 23
Average Turnaround Time : 35.2
Its limits are what motivated the rewrite: no arrival times, no Gantt chart, a header line that printed ProcesstBurst Time because of a missing backslash in "\tBurst", and a fixed array of 99 processes with no bounds check. The original is kept as legacy/old_rr_tick_loop.cpp (unchanged apart from one added header comment).
The earlier source code, kept for reference
// ============================================================
// Round Robin CPU Scheduling Algorithm in C++
// Preemptive: each process gets at most Q time units per round
// ============================================================
// LEGACY: the earlier version published on ankurm.com, kept for comparison (this header comment is the only addition).
// Its waiting times are right only when every process arrives at time 0.
#include <iostream>
using namespace std;
// Holds all attributes of a single process for Round Robin simulation
struct Process {
int processNo; // Process identifier (P1, P2, ...)
int totalBurstTime; // Original burst time (kept for final output and TT)
int remainingBurstTime; // Burst time still left to execute (decremented each tick)
int waitingTime; // Accumulated waiting time across all rounds
int turnaroundTime; // Total time from start to completion
int quantumRoundCount; // How many full time-quanta this process has already used
};
int main() {
Process processes[99];
int processCount;
// -------------------------------------------------------
// Step 1: Read number of processes and their burst times
// -------------------------------------------------------
cout << "\n Enter No of Processes: ";
cin >> processCount;
for (int i = 0; i < processCount; i++) {
cout << "\n Enter Burst Time of Process " << i + 1 << ": ";
cin >> processes[i].totalBurstTime;
processes[i].remainingBurstTime = processes[i].totalBurstTime; // Copy for simulation
processes[i].waitingTime = 0;
processes[i].turnaroundTime = 0;
processes[i].quantumRoundCount = 0;
processes[i].processNo = i + 1;
}
int timeQuantum;
cout << "\n Enter Time Quantum: ";
cin >> timeQuantum;
// Display entered data
cout << "\n\n Entered Data";
cout << "\n ProcesstBurst Time";
for (int i = 0; i < processCount; i++) {
cout << "\n " << processes[i].processNo
<< "\t\t" << processes[i].totalBurstTime;
}
// -------------------------------------------------------
// Step 2: Compute total simulation time (sum of all burst times)
// -------------------------------------------------------
int totalSimTime = 0;
for (int i = 0; i < processCount; i++) totalSimTime += processes[i].totalBurstTime;
// -------------------------------------------------------
// Step 3: Round Robin Simulation
// currentProc = index of process currently on CPU
// quantumTick = how many time units used in current quantum slot
// -------------------------------------------------------
int currentProc = 0;
int quantumTick = 0;
for (int tick = 0; tick < totalSimTime; tick++) {
// When a process begins a new round (quantum slot starts),
// record the current time as the start of its wait period
if (quantumTick == 0 && processes[currentProc].remainingBurstTime != 0) {
processes[currentProc].waitingTime = tick;
// Subtract all time this process has already spent executing in previous rounds
if (processes[currentProc].quantumRoundCount != 0) {
processes[currentProc].waitingTime -=
timeQuantum * processes[currentProc].quantumRoundCount;
}
}
if (processes[currentProc].remainingBurstTime != 0 && quantumTick != timeQuantum) {
// Process still has work to do and quantum not yet exhausted: run for 1 tick
processes[currentProc].remainingBurstTime--;
quantumTick++;
} else {
// Either quantum exhausted OR process finished — switch to next process
if (quantumTick == timeQuantum && processes[currentProc].remainingBurstTime != 0) {
// Process used a full quantum but is not finished yet
processes[currentProc].quantumRoundCount++;
}
// Move to next process in circular order
currentProc = (currentProc + 1) % processCount;
quantumTick = 0;
tick--; // Redo this tick with the newly selected process
}
}
// -------------------------------------------------------
// Step 4: Compute Turnaround Time and display results
// -------------------------------------------------------
int totalWaiting = 0, totalTurnaround = 0;
cout << "\n\n Result of Round Robin Scheduling";
cout << "\n PNo\tBT\tWT\tTT";
for (int i = 0; i < processCount; i++) {
processes[i].turnaroundTime = processes[i].waitingTime + processes[i].totalBurstTime;
totalWaiting += processes[i].waitingTime;
totalTurnaround += processes[i].turnaroundTime;
cout << "\n " << processes[i].processNo
<< "\t" << processes[i].totalBurstTime
<< "\t" << processes[i].waitingTime
<< "\t" << processes[i].turnaroundTime;
}
cout << "\n Average Waiting Time : " << (float)totalWaiting / processCount;
cout << "\n Average Turnaround Time : " << (float)totalTurnaround / processCount;
cout << endl;
return 0;
}
The earlier explanation of its code (original five points)
- totalBurstTime vs remainingBurstTime —
totalBurstTimestores the original burst time for computing TT and final output.remainingBurstTimeis decremented each tick during the simulation so the scheduler knows when a process is done. - Simulation loop — Runs for exactly
totalSimTimeticks. At each tick, if the current process has remaining work and has not exhausted its quantum, it executes for one unit. Otherwise the scheduler switches to the next process. - Waiting Time tracking — When a process enters a new quantum round, the current tick is stored as
waitingTime, and all its previous execution time (timeQuantum × quantumRoundCount) is subtracted to isolate true waiting time. - Circular scheduling —
(currentProc + 1) % processCountwraps back to process 0 after the last one, implementing the circular queue. - tick– — When switching processes, the current tick is “undone” so the next iteration processes the same clock cycle with the newly selected process instead of skipping a tick.
Note on point 3: quantumRoundCount counts only full quanta, which is exactly why the trick fails once a process can arrive late or run for less than Q before finishing a turn.
Viva and exam questions
Short answers you can give in an oral exam. Open any question to see the answer.
Q1. What is Round Robin scheduling?
A preemptive CPU scheduling algorithm in which each process runs for at most one time quantum and, if unfinished, goes to the back of the ready queue.
Q2. Is Round Robin preemptive or non-preemptive?
Preemptive: the running process is taken off the CPU when its quantum expires, even though it has work left.
Q3. Which data structure does it use?
A FIFO queue (circular queue) of ready processes.
Q4. What happens if the quantum is very large?
No process is preempted, so the algorithm behaves like FCFS. In the sweep above, every Q from 29 up gave the same average waiting time as FCFS: 28.00.
Q5. What happens if the quantum is very small?
Response time improves, but the CPU spends a large share of its time on context switches. In the sweep, Q=1 needed 45 Gantt boxes against 5 at Q=29.
Q6. Can a process starve under Round Robin?
No. Every ready process reaches the front of the queue after at most the slices of the (n − 1) processes ahead of it.
Q7. How do you compute waiting time and turnaround time?
TAT = CT − AT and WT = TAT − BT. For the first example: P2 has CT 61, AT 0, BT 29, so TAT 61 and WT 32.
Q8. What if a new process arrives exactly when a quantum expires?
It depends on the convention. This post and most textbooks put the new arrival into the queue before the preempted process. State your convention in the answer.
Q9. Why is the average waiting time of RR usually higher than SJF?
RR gives long jobs many turns and makes short jobs share the CPU with them, while SJF finishes short jobs first, which minimizes average waiting time. RR trades that for fairness and bounded response time.
Q10. How is the response time bounded?
A process waits at most (n − 1) × Q units before it first gets the CPU.
Q11. What is the context-switch overhead if Q = 4 and a switch costs 1 unit?
1 / (4 + 1) = 20% of the CPU time.
Q12. For which kind of system is Round Robin well suited?
Time-sharing and interactive systems where every user must see a quick response; less suited to batch workloads where average turnaround matters most.
Should you even use plain Round Robin? For learning, yes: it is the cleanest example of preemption and fairness. For a real scheduler, a single fixed quantum is rarely enough, since it ignores priorities and I/O behaviour. Production systems combine time slicing with priorities and multiple queues. Use plain RR when equal treatment of equal processes is the requirement, and pick Q from the typical burst length rather than from a fixed constant.
See also
- Implementing FCFS Scheduling Algorithm in C++
- Implementing SJF Scheduling Algorithm in C++
- Implementation of Priority Scheduling Algorithm in C++
Further reading
- Companion code: cs-lab-programs / os / round-robin (C++ and C sources, inputs, captured outputs, legacy program)
- Silberschatz, Galvin and Gagne, Operating System Concepts, chapter on CPU scheduling (Round Robin, time quantum and context-switch overhead)
Bottom line is…
Round Robin is the cornerstone of modern preemptive operating systems because it guarantees fairness and bounded response time for all processes. The critical design parameter is the time quantum: too small causes excessive context-switch overhead, too large makes it behave like FCFS. In the measured example the best average waiting time came from a quantum close to the typical burst (Q=12 against bursts of 3 to 29), not from the smallest or the largest value. RR is especially effective where response time matters — interactive terminals, web servers and GUI applications.
Why is this code imcomplete?
Code is updated!
code still has many issues ADS VIA CARBON
About • FAQ • Blog • Terms of Use • Contact Us • GDB Tutorial • Credits
2018 © GDB Online
Language
main.cpp
input
stderr
Compilation failed due to following error(s). main.cpp:12:11: error: ‘::main’ must return ‘int’
void main()
^
main.cpp: In function ‘int main()’:
main.cpp:16:5: error: ‘cout’ was not declared in this scope
cout<>np;
^
main.cpp:18:5: note: suggested alternative:
In file included from main.cpp:1:0:
/usr/include/c++/5/iostream:60:18: note: ‘std::cin’
extern istream cin; /// Linked to standard input
^
what is Pno denoting here?
what is no denoting here?
p[i].no is process number. You can say it is an unique identifier.
k & j & t ; what it is??
Dear #AnkurMhatre you did a great job..
It will be more clear and helpful if you edit your code with the sufficient human readable comments.
Best Regards
this code is giving error for the header file #include
Could you explain that, what is the purpose and working of these below lines?
.
————————————————————————
.
int rrg[99];
for(j=0;j<totaltime;j++)
{
if((k==0)&&(p[i].et!=0))
{
p[i].wt=j;
if((p[i].t!=0))
{
p[i].wt-=q*p[i].t;
}
}
if((p[i].et!=0)&&(k!=q))
{
rrg[j]=p[i].no;
p[i].et-=1;
k++;
}
else
{
if((k==q)&&(p[i].et!=0))
{
p[i].t+=1;
}
i=i+1;
if(i==np)
{
i=0;
}
k=0;
j=j-1;
}
}
.
.
________________________________________________________________________
What is "rrg"?
Can you please add comments next to ever variable i.e. what is the purpose of the variable? or their names ?
Hope you will reply soon.
hi
kindly tell the elaboration of np stc type of words pls
#include
using namespace std;
int main()
{
int wtime[10],btime[10],rtime[10],num,quantum,total;
cout<>num;
cout<<"Enter burst time";
for(int i=0;i<num;i++)
{ cout<<"\nP["<<i+1<>btime[i];
rtime[i] = btime[i];
wtime[i]=0;
}
cout<>quantum;
int rp = num;
int i=0;
int time=0;
cout<quantum)
{
rtime[i]=rtime[i]-quantum;
cout<<" | P["<<i+1<<"] | ";
time+=quantum;
cout<<time;
}
else if(rtime[i]0)
{time+=rtime[i];
rtime[i]=rtime[i]-rtime[i];
cout<<" | P["<<i+1<<"] | ";
rp–;
cout<<time;
}
i++;
if(i==num)
{
i=0;
}
}
system("pause");
return 0;
}