Understanding Shortest Job First (SJF) Scheduling in C Programming
Shortest Job First (SJF) is a popular scheduling algorithm used in operating systems to manage the execution of processes efficiently. In this article, we will explore the basics of SJF scheduling and implement a simple SJF program in C that is easy to understand for both beginners and intermediate learners.
Understanding SJF Scheduling:
SJF scheduling is based on the principle of selecting the shortest job from the ready queue for execution. The idea is to minimize the waiting time and turnaround time of processes, leading to improved system performance.
Key Concepts:
Burst Time:
- Burst time refers to the time taken by a process to complete its execution.
- In SJF scheduling, processes with the shortest burst time are given priority.
Ready Queue:
- The ready queue is a queue that holds processes ready to be executed.
- Processes are scheduled based on their burst time, with the shortest job at the front of the queue.
C Program for SJF Scheduling:
Now, let's implement a simple SJF scheduling program in C:
#include <stdio.h> void findWaitingTime(int processes[], int n, int bt[], int wt[]) { wt[0] = 0; for (int i = 1; i < n; i++) wt[i] = bt[i - 1] + wt[i - 1]; } void findTurnaroundTime(int processes[], int n, int bt[], int wt[], int tat[]) { for (int i = 0; i < n; i++) tat[i] = bt[i] + wt[i]; } void findAverageTime(int processes[], int n, int bt[]) { int wt[n], tat[n]; findWaitingTime(processes, n, bt, wt); findTurnaroundTime(processes, n, bt, wt, tat); float total_wt = 0, total_tat = 0; for (int i = 0; i < n; i++) { total_wt += wt[i]; total_tat += tat[i]; } float avg_wt = total_wt / n; float avg_tat = total_tat / n; printf("Average Waiting Time: %.2f\n", avg_wt); printf("Average Turnaround Time: %.2f\n", avg_tat); } void sjfScheduling(int processes[], int n, int bt[]) { // Sort processes based on burst time for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (bt[j] > bt[j + 1]) { // Swap burst time int temp = bt[j]; bt[j] = bt[j + 1]; bt[j + 1] = temp; // Swap process IDs temp = processes[j]; processes[j] = processes[j + 1]; processes[j + 1] = temp; } } } // Print order of execution printf("Order of Execution: "); for (int i = 0; i < n; i++) printf("P%d ", processes[i]); printf("\n"); // Calculate and print average waiting and turnaround time findAverageTime(processes, n, bt); } int main() { // Example: Three processes with burst times int processes[] = {1, 2, 3}; int n = sizeof(processes) / sizeof(processes[0]); int burst_time[] = {6, 8, 2}; sjfScheduling(processes, n, burst_time); return 0; }Explanation:
Comments
Post a Comment