Preemptive Shortest Job First (SJF) - scheduling algorithm in C

Exploring Preemptive SJF Algorithm in C

TheLazyBusyCoder's Blog

Welcome to my coding adventures! In this post, we'll explore a C program.

Preemptive Shortest Job First (SJF) - scheduling algorithm in C

Check out my YouTube video explaining this code: Watch now

   
    
        
#include <stdio.h>
#include <stdlib.h>

typedef struct process
{
  int id, at, bt, ct , wt, tat, rt;
} process;
void display(process pro[], int n)
{
	printf("P  AT BT CT TAT WT  \n");
	for (int i = 0; i < n; i++)
	{
		printf("P%d %2d %2d %2d %2d %2d\n",
				pro[i].id,
				pro[i].at,
				pro[i].bt,
				pro[i].ct,
				pro[i].tat,
				pro[i].wt);
	}
}
void preemptiveSJF(process proc[], int n, int tq)
{
  int i = 0;
  int time = 0;
  int p = n;
  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].rt < proc[min].rt) {
				  min = i;
			  }
		  }
	  }
	  if(min == -1) time++;
	  else if(proc[min].rt <= tq) {
		  time += proc[min].rt;
		  proc[min].rt = 0;
		  proc[min].ct = time;
		  p--;
	  } else {
		  proc[min].rt -= tq;
		  time += tq;
	  }
  }
  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("Average TAT: %.2f\nAverage WT: %.2f\n" , (ttat * 1.0) / n , (twt * 1.0) / n);
}

int main()
{
  process proc[10];
  int n, i, tq;
  printf("Enter number of processes: ");
  scanf(" %d", &n);
  for (i = 0; i < n; i++)
  {
    printf("\n");
    printf("Arrival time for P%d: ", i + 1);
    scanf(" %d", &proc[i].at);
    printf("Burst time for P%d: ", i + 1);
    scanf(" %d", &proc[i].bt);
    proc[i].rt = proc[i].bt;
	proc[i].ct = proc[i].tat = proc[i].wt = 0;
    proc[i].id = i + 1;
  }
  printf("Enter time quantum for preemption: ");
  scanf(" %d", &tq);
  preemptiveSJF(proc, n, tq);
  return 0;
}
        
    

Comments

Popular posts from this blog

Least Recently Used (LRU) page algorithm in c

Optimal Page Replacement (OPT) in C

LFU Page Replacement Algorithm in C