Round Robin CPU Scheduling Program in C

Tasks take turns around a processor in round robin scheduling.
Tasks take turns around a processor in round robin scheduling.

Round Robin is a preemptive operating systems CPU scheduling algorithm that assigns each process a fixed cyclic time slice called a time quantum.

Round Robin prevents CPU starvation and provides fair response times in interactive operating systems.

This C program calculates Waiting Time (WT), Turnaround Time (TAT), and system throughput metrics.

Interactive Runnable C Implementation

#include <stdio.h>
#include <stdbool.h>

struct Process {
    int id;
    int burst_time;
    int remaining_time;
    int waiting_time;
    int turnaround_time;
};

void calculate_round_robin(struct Process p[], int n, int quantum) {
    int current_time = 0;
    bool done;

    for (int i = 0; i < n; i++) {
        p[i].remaining_time = p[i].burst_time;
    }

    do {
        done = true;
        for (int i = 0; i < n; i++) {
            if (p[i].remaining_time > 0) {
                done = false;

                if (p[i].remaining_time > quantum) {
                    current_time += quantum;
                    p[i].remaining_time -= quantum;
                } else {
                    current_time += p[i].remaining_time;
                    p[i].waiting_time = current_time - p[i].burst_time;
                    p[i].remaining_time = 0;
                }
            }
        }
    } while (!done);

    for (int i = 0; i < n; i++) {
        p[i].turnaround_time = p[i].burst_time + p[i].waiting_time;
    }
}

int main(void) {
    struct Process proc[] = {
        {1, 10, 0, 0, 0},
        {2, 5,  0, 0, 0},
        {3, 8,  0, 0, 0}
    };
    int n = sizeof(proc) / sizeof(proc[0]);
    int time_quantum = 2;

    calculate_round_robin(proc, n, time_quantum);

    printf("PID\tBurst\tWaiting\tTurnaround\n");
    float total_wt = 0, total_tat = 0;
    for (int i = 0; i < n; i++) {
        total_wt += proc[i].waiting_time;
        total_tat += proc[i].turnaround_time;
        printf("P%d\t%d\t%d\t%d\n", proc[i].id, proc[i].burst_time, proc[i].waiting_time, proc[i].turnaround_time);
    }

    printf("\nAverage Waiting Time = %.2f\n", total_wt / n);
    printf("Average Turnaround Time = %.2f\n", total_tat / n);
    return 0;
}

Open example in compiler

Expected Output

PID	Burst	Waiting	Turnaround
P1	10	13	23
P2	5	10	15
P3	8	13	21

Average Waiting Time = 12.00
Average Turnaround Time = 19.67

Frequently Asked Questions

What happens if the time quantum is extremely large?

The Round Robin scheduling algorithm behaves identically to non-preemptive First-Come First-Served (FCFS) scheduling.

Related examples