Write a program using C to implement preemptive priority based scheduling algorithm.
Below is the C program that implements a Preemptive Priority-Based Scheduling algorithm. In this version, a process with a higher priority (lower numerical value) can preempt a currently running process if it arrives while the running process is still executing.
#include <stdio.h>
struct Process {
int id; // Process ID
int burst; // Burst time
int remaining; // Remaining time
int priority; // Priority
int waiting; // Waiting time
int turnaround; // Turnaround time
};
// Function to calculate waiting and turnaround times
void calculateTimes(struct Process processes[], int n) {
int total_waiting = 0, total_turnaround = 0;
for (int i = 0; i < n; i++) {
processes[i].turnaround = processes[i].waiting + processes[i].burst;
total_turnaround += processes[i].turnaround;
total_waiting += processes[i].waiting;
}
printf("Average Waiting Time: %.2f\n", (float)total_waiting / n);
printf("Average Turnaround Time: %.2f\n", (float)total_turnaround / n);
}
// Function to find the index of the process with the highest priority
int findHighestPriorityProcess(struct Process processes[], int n, int current_time) {
int idx = -1;
for (int i = 0; i < n; i++) {
if (processes[i].remaining > 0 && processes[i].priority < (idx == -1 ? 1000 : processes[idx].priority)) {
idx = i;
}
}
return idx;
}
int main() {
int n;
// Read the number of processes
printf("Enter the number of processes: ");
scanf("%d", &n);
struct Process processes[n];
// Read process burst times and priorities
for (int i = 0; i < n; i++) {
processes[i].id = i + 1; // Assign Process ID
printf("Enter burst time for Process %d: ", i + 1);
scanf("%d", &processes[i].burst);
printf("Enter priority for Process %d (lower number means higher priority): ", i + 1);
scanf("%d", &processes[i].priority);
processes[i].remaining = processes[i].burst; // Initialize remaining time
}
int current_time = 0;
int completed = 0;
// Process scheduling loop
while (completed < n) {
int idx = findHighestPriorityProcess(processes, n, current_time);
if (idx != -1) {
// Process the highest priority job
processes[idx].remaining--;
current_time++;
// Check if the process is completed
if (processes[idx].remaining == 0) {
processes[idx].turnaround = current_time; // Turnaround time
processes[idx].waiting = processes[idx].turnaround - processes[idx].burst; // Waiting time
completed++;
}
} else {
current_time++; // No process is ready, just increment time
}
}
// Calculate and display final times
calculateTimes(processes, n);
// Print the process details
printf("\nProcess ID\tBurst Time\tPriority\tWaiting Time\tTurnaround Time\n");
for (int i = 0; i < n; i++) {
printf("%d\t\t%d\t\t%d\t\t%d\t\t%d\n",
processes[i].id, processes[i].burst,
processes[i].priority, processes[i].waiting,
processes[i].turnaround);
}
return 0;
}