Wednesday, March 14, 2012

Short Job First Non PREEMPTIVE with arrival time CPU Scheduling Algorithm in C Source code program

 #include <stdio.h>  
#include <conio.h>
/* Short Job First NON PREEMPTIVE CPU Scheduling Algorithm
By Suraj Jha & Abhas Tandon
Please note that program has some extra printf statements that were used for debugging
They can be removed if required
*/
int n;
struct sjf{
int sr;
int wt,bt,at,tat;
int flag;
}arr[10];
struct sjf queue[15];
int f=-1,r=-1;
void enqueue(struct sjf x){
if(f==-1 && r==-1)
{
queue[++f]=x;
r++;
}
else{
queue[++r]=x;
}
printf("Added %d to queue\n",queue[r].sr);
}
int dequeue(){
int x=f;
if(f==r)
f=r=-1;
else
f++;
printf("Dequeue %d\n",queue[x].sr);
return queue[x].sr;
}
void sortQueue(){
int i,j;
for(i=f;i<=r;i++)
{
for(j=i+1;j<=r;j++) {
if(queue[i].bt>queue[j].bt)
{
struct sjf temp= queue[i];
queue[i]=queue[j];
queue[j]=temp;
}
}
}
}
void dispq(){
int i;
if(f==-1)
printf("Empty");
for(i=f;i<=r;i++)
printf("%d ",queue[i].sr);
printf("\n%d %d\n",f,r);
}
float awt,atat;
void input(){
printf("Enter Number of processes:");
scanf("%d",&n);
int i;
for(i=0;i<n;i++)
{
printf("Enter Burst Time of process %d:",i+1);
scanf("%d",&arr[i].bt);
printf("Enter Arrival Time of process %d:",i+1);
scanf("%d",&arr[i].at);
arr[i].sr=i;
arr[i].flag=0;
}
}
void calculate(){
int i,j,btto;
arr[0].wt=0;
//arr[0].flag=1;
int btt=arr[0].bt;
arr[0].tat=arr[0].bt;
atat=arr[0].bt;
i=0;
do{
printf("Start of Do While\n");
for(j=1;j<n;j++){
printf("cmp arr[j] %d btt %d jFlag %d\n",arr[j].at,btt,arr[j].flag);
if(arr[j].at<btt )
enqueue(arr[j]);
}
sortQueue();
printf("Sorted Queue\n");
btto=btt;//Starting time for this process
printf("Btto=%d\n",btto);
int pid=dequeue();
while(arr[pid].flag==1){
pid=dequeue();
}
btt+=arr[pid].bt;
printf("After Adding %d btt =%d\n",queue[f].bt,btt);
arr[pid].flag=1;//to show that process is executed
printf("%d Process %d executed",i,pid);
arr[pid].wt=btto - arr[pid].at;
arr[pid].tat= arr[pid].bt+ arr[pid].wt;
printf("A %d %d %d %d\n",btto,arr[pid].at,arr[pid].bt,arr[pid].wt);
awt+=arr[pid].wt;
atat+= arr[pid].tat;
//printf("%d %d\n",f,r);
i++;
printf("I incremented\n");
dispq();
while(f!=-1)
dequeue();
printf("Queue refresed Ready for next run\n");
}while(i<n-1);
awt/=n;
atat/=n;
}
void display(){
int i;
printf("SR.\tA.T.\tB.T.\tW.T.\tT.A.T.\n");
for(i=0;i<n;i++)
{
printf("%3d\t%3d\t%3d\t%3d\t%4d\n",i+1,arr[i].at,arr[i].bt,arr[i].wt,arr[i].tat);
}
printf("Average Waiting Time: %f\nAverage Turn Around Time:%f",awt,atat);
}
int main(){
printf("SJF CPU Scheduling Algorithm\n");
input();
calculate();
display();
getch();
}

1 comment: