/* 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 #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; }