//************************************** // Name: Banker's algorithm // Description:Illustrate banker's algorithm // By: Puneet Jindal // //This code is copyrighted and has// limited warranties.
Please see http://www.Planet-Source-Code.com/vb
/scripts/ShowCode.asp?
txtCodeId=13616&lngWId=3//for details.//
************************************** #include<iostream> using namespace std; // Tells whether a given sequence is safe or not class Banker { int total_processes; int remaining_processes; int A_avail,B_avail,C_avail; int A,B,C; class Process { private: int allocated[3]; int max_needed[3]; public: Process() { allocated[0] = allocated[1] =
allocated[2] = max_needed[0] = max_needed[1] = max_needed[2] =
0; cout<<"Enter the
allocated resources of types A,B and C"<<endl;
cin>>allocated[0]
>>allocated[1]>>allocated[2];
cout<<"Enter the
maximum number of
resources needed for each of types A,B and
C"<<endl; cin>>max_needed[0]
>>max_needed[1]>>max_needed[2];
} int Allocated(int temp)
{ return allocated[temp];
} int Need(int temp)
{ return max_needed[temp] -
allocated[temp];
} int Max(int temp)
{ return max_needed[temp];
} }; Process *process;
int *sequence;
public:
Banker()
{ A_avail = B_avail = C_avail = 0 ;
A = B = C = 0 ;
process = NULL;
sequence = NULL;
total_processes =
remaining_processes = 0; int a,b,c; a = b = c = 0; cout<<"Available resources
of type A,B
and C"<<endl;
cin>>A_avail>>B_avail>>
C_avail; cout<<"Enter the total number of
processes"<<endl;
cin>>total_processes;
remaining_processes = total_processes;
sequence = new int[total_processes];
cout<<"Please enter the required
information of indivisual processes"<<endl;
process = new Process[total_processes];
cout<<"Enter the sequence(0,1,2 ...
so on[in this format])"<<endl;
for(int i = 0 ; i < total_processes ; ++i)
{ cin>>sequence[i];
a += process[i].Allocated(0);
b += process[i].Allocated(1);
c += process[i].Allocated(2);
} // Calculating total number of
resources of each type
A = A_avail + a;
B = B_avail + b;
C = C_avail + c;
bool safe = true;
for(int i = 0 ; i < total_processes ; ++i)
//
Check fesibility of each process
{ if( process[sequence[i]].Need(0)
<= A_avail
&& process[sequence[i]].Need(1) <=
B_avail && process[sequence[i]].Need(2) <= C_avail )
{ // i'th process can be
executed safely
A_avail += process
[sequence[i]].Allocated(0);
B_avail += process
[sequence[i]].Allocated(1);
C_avail += process
[sequence[i]].Allocated(2);
} else
{ safe = false;
cout<<"Unsafe condition
encountered
after "<<i<<" process"<<endl; return;
} } if(safe == true)
{ cout<<"Sequence is safe"<<endl;
if(! (A_avail == A && B_avail == B
&& C_avail == C) )
cout<<"Error encountered in
the procedure.Not
all resources
deallocated."<<endl;
} } ~Banker()
{ delete []process;
delete []sequence;
} }; int main()
{ Banker b;
return 0;
}