Priority scheduling
// Priority scheduling
#include <stdio.h>
struct Process { int pid, arrival, burst, priority,
completion, turnaround, waiting, response;};
void sortProcesses (struct Process p[], int n) {
for (int i = 0; i<n-1; i++) {
for (int j=0; j < n - i – 1;j++) {
if (p[j].arrival > p[j + 1] .arrival ||
(p[j].arrival == p[j + 1] .arrival &&
p[j].priority > p[j+1].priority))
struct Process temp = p[j];
p[j] = p[j + 1];p[j+1]= temp; }}}}
void calculateTimes(struct Process p[], int n) {
int currentTime = 0, completed = 0, visited[n];
for (int i=0; i < n; i++) visited[i] = 0;
while (completed < n) {
int idx = -1, minPriority=1e9;
for (int = 0; i < n; i++) {
if (!visited[i] && p[1].arrival <= currentTime
&& p[i].priority < minPriority){
idx = i;
minPriority = p[i].priority; }}
if (idx != -1) { visited[idx]
= 1;
if (currentTime < p[idx].arrival) currentTime =
p[idx].arrival;
p[idx].response = currentTime - p[idx].arrival;
p[idx].completion = currentTime + p[idx].burst;
p[idx].turnaround = p[idx].completion - p[idx].arrival;
p[idx].waiting = p[idx].turnaround - p[idx].burst;
currentTime += p[idx].burst;
completed++; }
else {
currentTime++; }}}
void printTable ( struct Process p[], int n) {
float totalTAT = 0, totalWT=0, totalRT = 0;
printf("\nPID\tArrival\tBurst\tPriority\tCompletion\tTAT\tWT\tRT\n");
for (int i = 0; i < n; i++) {
totalTAT += p[i].turnaround;
totalWT += p[i].waiting;
totalRT += p[i].response;
printf("%d\t%d\t%d\t%d\t\t%d\t\t%d\t%d\t%d\n",
p[i].pid, p[i].arrival, p[i].burst, p[i].priority,
p[i].completion, p[i].turnaround, p[i].waiting, p[i].response); }
printf("\nAverage Turnaround Time: %.2f",
totalTAT / n);
printf("\nAverage Waiting Time: %.2f", totalWT
/ n);
printf("\nAverage Response Time: %.2f\n",
totalRT / n); }
int main() { int
n;
printf("Enter number of processes: "); scanf("%d", &n);
struct Process p[n];
for (int i = 0; i < n; i++) {
p[i].pid=i+1;
printf("\nProcess %d Arrival Time: ", i + 1); scanf("%d", &p[i].arrival);
printf("Process %d Burst Time: ", i + 1); scanf("%d",
&p[i].burst);
printf("Process %d Priority (lower is higher):
", i + 1); scanf("%d",
&p[i].priority); }
sortProcesses(p, n);
calculateTimes (p, n);
printTable(p, n);
return 0; }
Comments
Post a Comment