Non Preemptive Priority Algorithm in C
TheLazyBusyCoder's Blog
Welcome to my coding adventures! In this post, we'll explore a C program.
Exploring Non Preemptive Priority - scheduling algorithm in C
Check out my YouTube video explaining this code: No Video
#include <stdio.h>
#include
typedef struct process {
int id , at , bt ,p,rt, ct , tat , wt;
} process;
void display(process proc[] , int n) {
int i;
printf("\n\nP AT BT P CT TAT WT\n");
for(i = 0; i < n; i++) {
printf("P%d %2d %2d %2d %2d %2d %2d\n" ,
proc[i].id,
proc[i].at,
proc[i].bt,
proc[i].p,
proc[i].ct,
proc[i].tat,
proc[i].wt
);
}
}
void nonp(process proc[] , int n) {
int p = n;
int i , j;
int time = 0;
while(p > 0) {
int min = -1;
for(i = 0; i < n; i++) {
if(proc[i].at <= time && proc[i].rt > 0) {
if(min == -1 || proc[i].p < proc[min].p) {
min = i;
}
}
}
if(min == -1) time++;
else {
time += proc[min].rt;
proc[min].ct = time;
proc[min].rt = 0;
p--;
}
}
int ttat = 0;
int twt = 0;
for(i = 0; i < n; i++) {
proc[i].tat = proc[i].ct - proc[i].at;
proc[i].wt = proc[i].tat - proc[i].bt;
ttat += proc[i].tat;
twt += proc[i].wt;
}
display(proc , n);
printf("\nAvg TAT %0.2f\nAvg WT %0.2f\n" , (ttat * 1.0) / n , (twt * 1.0) / n);
}
int main() {
int n;
printf("Enter number of process: ");
scanf(" %d" , &n);
process proc[n];
int i;
for(i = 0; i < n; i++) {
proc[i].id = i+1;
printf("\nFor P%d\n", i+1);
printf("Enter AT: ");
scanf(" %d" , &proc[i].at);
printf("Enter BT: ");
scanf(" %d" , &proc[i].bt);
printf("Enter P: ");
scanf(" %d" , &proc[i].p);
proc[i].rt = proc[i].bt;
proc[i].ct = proc[i].tat = proc[i].wt = 0;
}
nonp(proc , n);
return 0;
}
// 4 1 5 1 2 3 2 3 6 1 4 2 3
Comments
Post a Comment