Saturday, April 17, 2010

Banker's Algorithm

//add header files stdio.h and conio.h
#include
#include

int AVAILABLE[4];
int MAX[3][4];
int ALLOCATION[3][4];
int NEED[3][4];
int REQUEST[3][4];

int safestate(void)
{
int i,j,k;
int WORK[4];
int FINISH[3]={0,0,0};
int SAFE=1;

for(j=0;j<4;j++)
WORK[j]=AVAILABLE[j];

for(i=0;i<3;i++)
{
if(FINISH[i]==0)
{
for(j=0;j<4;j++)
if(NEED[i][j]>WORK[j])
break;
if(j==4)
{
FINISH[i]=1;
for(k=0;k<4;k++)
WORK[j]=WORK[j]+ALLOCATION[i][k];
}
}
}

for(i=0;i<3;i++)
{
if(FINISH[i]==0)
{
SAFE=0;
break;
}
}
return(SAFE);
}

void main(void)
{
int i,j;
char ans='n';
int state=0;
clrscr();
printf("\n System has three processes and four types of resources");

printf("\n Enter four AVAILABLE matrix values:");
for(i=0;i<4;i++)
scanf("%d",&AVAILABLE[i]);

printf("\n Enter MAXIMUM required resources for each process:");
for(i=0;i<3;i++)
{
printf("\n P%d:",i+1);
for(j=0;j<4;j++)
scanf("%d",&MAX[i][j]);
}

printf("\n Enter currently ALLOCATED resources for each process:");
for(i=0;i<3;i++)
{
printf("\n P%d:",i+1);
for(j=0;j<4;j++)
scanf("%d",&ALLOCATION[i][j]);
}

printf("\nTHE NEED MATRIX\N ");
printf("\n\t R1\tR2\tR3\tR4");
for(i=0;i<3;i++)
{
printf("\n P%d:",i+1);
for(j=0;j<4;j++)
{
NEED[i][j]=MAX[i][j]-ALLOCATION[i][j];
printf("\t%d",NEED[i][j]);
}
}
state=safestate();
if(state==1)
{
printf("\x07");
printf("\n System is in safe state");
printf("\n Do u want to process request?");
scanf(" %c",&ans);
if(ans=='y' || ans=='Y')
{
printf("\n Which process requesting resources? P");
scanf("%d",&i);
printf("\n Enter REQUEST for process P%d :",i);
for(j=0;j<4;j++)
scanf("%d",&REQUEST[i][j]);
for(j=0;j<4;j++)
{
if(NEED[i][j]
{
printf("requesting resources more than needed!!");
exit(1);
}
}
for(j=0;j<4;j++)
{
if(REQUEST[i][j]>AVAILABLE[j])
{
printf("Resources are not available at this time!!");
exit(1);
}
}

for(j=0;j<4;j++)
{
ALLOCATION[i][j]=ALLOCATION[i][j]+REQUEST[i][j];
AVAILABLE[j]=AVAILABLE[j]-REQUEST[i][j];
}
state=safestate();
if(state==1)
{
printf("\n Request is granted");
}
else
{
for(j=0;j<4;j++)
{
ALLOCATION[i][j]=ALLOCATION[i][j]-REQUEST[i][j];
AVAILABLE[j]=AVAILABLE[j]+REQUEST[i][j];
}
printf("\n Request can not be safely allocated!!");
}
}
}
else
{printf("\x07");
printf("\n System is in unsafe state"); }
getch();
}
/*
OUTPUT:
System has three processes and four types of resources
Enter four AVAILABLE matrix values:1 2 3 4

Enter MAXIMUM required resources for each process:
P1:1 0 3 2

P2:1 2 4 6

P3:2 3 4 5

Enter currently ALLOCATED resources for each process:
P1:1 0 1 1

P2:2 1 3 4

P3:1 2 0 1

THE NEED MATRIXN
R1 R2 R3 R4
P1:   0 0 2 1
P2: -1 1 1 2
P3:   1 1 4 4
System is in unsafe state
*/

0 comments:

Post a Comment

 
ShareThis

Visitor

Website counter
Copyright 2009 Code's. Powered by Blogger
Blogger Templates created by Deluxe Templates
Wordpress by Wpthemescreator
Blogger Showcase