Edição didática em português. O código e suas saídas preservam o original.
Escalonamento Round Robin em C
Simule turnos de CPU com um quantum e calcule tempos sem confundir duração e espera.

Round Robin concede a cada processo pronto um tempo máximo chamado quantum. Se não terminar, volta ao final da fila com seu tempo restante. O quantum precisa ser positivo para a simulação avançar.
Em cada turno, execute o mínimo entre quantum e tempo restante. Registre quando cada processo termina. O tempo de retorno é conclusão menos chegada; a espera é retorno menos tempo de CPU, sob as hipóteses do modelo.
Confira se o exemplo supõe que todos chegam no instante zero. Para chegadas diferentes, é preciso gerenciar a fila de prontos e períodos sem trabalho. A simulação didática não inclui necessariamente o custo real de troca de contexto.
Código C
#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;
}Abrir no compiladorSaída esperada
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
Perguntas frequentes
Por que o código e a saída continuam em inglês?
Palavras-chave, identificadores e textos verificados pelos testes são preservados para não alterar o programa. As explicações e os controles estão traduzidos.