// Program:
Bankers algorithm
#include<stdio.h>
#include<conio.h>
#include<math.h>
int m,n;
int avl[20];
int max[20][20];
int need[20][20];
int allocat[20][20];
int finish[20];
int work[20];
int ssindex;
int safe_seq[20];
void find_need();
void get_data(int mat[20][20]);
void safety_algorithm(int p);
int chk_safe();
void resource_request();
void main()
{
int flag=0;
int r,p,i;
clrscr();
printf("\nHow
many process u want:");
scanf("%d",&n);
printf("\n
How many resources u want:");
scanf("%d",&m);
printf("\n
Enter allocation matrix");
get_data(allocat);
printf("\nEnter
max matrix");
get_data(max);
printf("\nenter
available resources:");
for(r=0;r<m;r++)
scanf("%d",&avl[r]);
find_need();
for(r=0;r<m;r++)
{
work[r]=avl[r];
finish[r]=0;
}
for(p=0;p<n;p++)
{
flag=0;
for(r=0;r<m;r++)
if(need[p][r]>work[r])
{
flag=1;
break;
}
if(flag==0)
{
safety_algorithm(p);
finish[p]=1;
safe_seq[ssindex]=p;
ssindex++;
}
}
getch();
printf("safe
sequence is:");
printf("<");
for(i=0;i<ssindex;i++)
printf("p%d
",safe_seq[i]);
printf(">\n\n");
if(chk_safe())
printf("\nEntered
sequence is safe:");
else
printf("\nEntered
sequence is not safe:");
getch();
//printf("Enter
process id for request:");
//scanf("%d",&p);
printf("\nEnter
request for %d resources",m);
//for(r=0;r<m;r++)
//for(p=0;p<n;p++)
for(r=0;r<m;r++)
scanf("%d",&max[p][r]);
resource_request();
}//main
void find_need()
{
int p,r;
for(p=0;p<n;p++)
for(r=0;r<m;r++)
need[r][p]=max[p][r]-allocat[p][r];
//need=max_requirement-currnt_allocation
}
void get_data(int mat[20][20])
{
int r,p;
for(p=0;p<n;p++)
for(r=0;r<m;r++)
scanf("%d",&mat[p][r]);
}
void safety_algorithm(int p)
{
int r=0;
for(r=0;r<m;r++)
work[r]=work[r]+allocat[p][r];
}
int chk_safe()
{
int i;
for(i=0;i<n;i++)
if(finish[i]==0)
return(0);
return(1);
}
void resource_request()
{
int r,p;
for(r=0;r<m;r++)
if(max[p][r]>need[r][p])
{
printf("\n
Process has exceeded it's max limit");
getch();
exit(0);
}//if
for(r=0;r<m;r++)
if(max[p][r]>avl[r])
{
printf("\n
Resourses are not available pricess should wait");
getch();
exit(0);
}//if
for(r=0;r<m;r++)
{
avl[r]-=max[p][r];
allocat[r][p]+=max[p][r];
need[r][p]-=max[p][r];
}//for
if(chk_safe())
{
printf("\n
Request can be imidiately granted");
//printf_safe();
getch();
}
else
{
printf("\n
Request can not be granted");
getch();
}
}
/* OUTPUT:
How many process u want:5
How many resources u want:4
Enter allocation matrix:
0 6 3 2
0 0 1 2
1 0 0 0
1 3 5 4
0 0 1 4
Enter max matrix:
0 6 5 2
0 0 1 2
1 7 5 0
2 3 5 6
0 6 5 6
Enter available resources:3 14 12 12
safe sequence is:<p0 p1 p2 p3 p4 >
Entered sequence is safe:
Enter request for 4 resources 1 2 0 1
Process has exceeded it's max limit
*/