转载自:http://apt-blog.net/object_oriented_bankers_alogrithm
#include <list>
#include <iostream>
using namespace std;
/* “资源”类,包含A、B、C、D四种“资源”
*/
class Resource{
private:
int A;
int B;
int C;
int D;
public:
Resource(int A, int B, int C, int D);
Resource operator + (const Resource &res);
Resource operator - (const Resource &res);
void operator = (const Resource &res);
bool operator <= (const Resource &res);
//便于stream输出
friend ostream &
operator << ( ostream & os, const Resource & obj )
{
os << "A:" << obj.A << " B:" << obj.B <<
" C:" << obj.C << " D:" << obj.D << endl;
return os;
}
};
Resource::Resource(int A, int B, int C, int D)
{
this->A = A;
this->B = B;
this->C = C;
this->D = D;
}
Resource
Resource:: operator + (const Resource &res)
{
int A = this->A + res.A;
int B = this->B + res.B;
int C = this->C + res.C;
int D = this->D + res.D;
return Resource(A, B, C, D);
}
Resource
Resource:: operator - (const Resource &res)
{
int A = this->A - res.A;
int B = this->B - res.B;
int C = this->C - res.C;
int D = this->D - res.D;
return Resource(A, B, C, D);
}
void
Resource::operator = (const Resource &res)
{
this->A = res.A;
this->B = res.B;
this->C = res.C;
this->D = res.D;
}
bool
Resource::operator <= (const Resource &res)
{
return (this->A <= res.A) && (this->B <= res.B) &&
(this->C <= res.C) && (this->D <= res.D);
}
/*“线程”类,带有该“线程”当前拥有的资源Current和“线程”的最大需求Maxmum
*/
class Process {
public:
int id;
Resource Maxmum;
Resource Current;
public:
Process(int i, const Resource &Max, const Resource &Cur);
friend ostream &
operator << ( ostream & os, const Process & obj )
{
os << "Process " << obj.id << "n" << "MAX " << obj.Maxmum <<
"CUR " << obj.Current;
return os;
}
};
Process::Process(int i, const Resource &Max, const Resource &Cur):
id(i), Maxmum(Max), Current(Cur){}
/*
* 银行家算法实现函数
*/
int
BankerAlgorithm ()
{
Resource SystemAvaliable(3,1,0,2);
list<Process> Processes;
Processes.push_back(
//构建一个“进程”,参数分别为“进程号、当前拥有资源、最大需求资源“
Process(1,Resource(3,3,2,2),Resource(1,2,0,1)));
Processes.push_back(
Process(2,Resource(1,2,3,4),Resource(1,2,3,3)));
Processes.push_back(
Process(3,Resource(1,1,5,0),Resource(1,1,2,0)));
while( !Processes.empty() ) {
bool found = false;
list<Process>::iterator i = Processes.begin();
while ( i != Processes.end() ) {
cout << "---System " << SystemAvaliable;
cout << "---For Process "<< i->id << ": n" << *i;
if(i->Maxmum - i->Current <= SystemAvaliable) {
cout << "---Process " << i->id
<< " Could be Terminated.n" << endl;
SystemAvaliable = SystemAvaliable + i->Current;
Processes.erase(i);
found = true;
break;
}
else {
cout << "---Process " << i->id <<
" Could NOT be Terminated Now.n" << endl;
++i;
}
}
if( !found ){
cout << "Fail, It's an UNSAFE state." << endl;
return 1;
}
}
cout << "OK, It's a SAFE state." << endl;
return 0;
}
int main ( int argc, char *argv[] )
{
BankerAlgorithm();
getchar();
getchar();
return 0;
}