C: simulating round-robin scheduling

Round-robin scheduling runs each ready process for at most one quantum and then moves on to the next, cycling until all are done. A process that has not finished waits for its next turn, so no job can monopolize the CPU. The turnaround time of a job is its completion time minus its arrival time.

C
#include <stdio.h>

int main(void) {
  int remaining[] = {5, 3, 1};
  int finish[] = {0, 0, 0};
  int jobs = 3;
  int quantum = 2;
  int clock = 0;
  int unfinished = jobs;

  while (unfinished > 0) {
    for (int i = 0; i < jobs; i++) {
      if (remaining[i] == 0) {
        continue;
      }
      int run = remaining[i] < quantum ? remaining[i] : quantum;
      clock += run;
      remaining[i] -= run;
      printf("t=%d P%d ran %d\n", clock, i + 1, run);
      if (remaining[i] == 0) {
        finish[i] = clock;
        unfinished--;
      }
    }
  }

  double total = 0;
  for (int i = 0; i < jobs; i++) {
    printf("P%d turnaround %d\n", i + 1, finish[i]);
    total += finish[i];
  }
  printf("average turnaround %.2f\n", total / jobs);
  return 0;
}
Read the full lesson