//// globle variables
struct Process{
bool exist; // the flag the process exsitence
int possess[MAX_RESOURCE]; //resources possessed
int require[MAX_RESOURCE]; // the requried resources
}Pro[MAX_PROCESS];
int nr; // number of resources
int np; // number of process
int total[MAX_RESOURCE]; // total resources vertex
int free[MAX_RESOURCE]; // free resources vertex
// test whether the process could be finished
bool CouldFinish ( struct Process * p ) {
int i;
for ( i=0; i<nr; i++ )
if ( p->require[i] > free[i] ) // require more than possible return false;
return true;
}
// finish the process
void Finish ( struct Process * p ) {
int i;
for ( i=0; i<nr; i++ )
free[i]+=p->possess[i]; // release the resources
p->exist = false; // delect the process
}
//////////// function ShowState current state
void ShowState( void ) {
int p,i;
cout<<"----------------------------------\n";
for ( i=0; i<nr; i++ ){
cout<<" "<<free[i]<<"\t";
for ( p=0; p<np; p++ )
if ( Pro[p].exist )
cout<<Pro[p].possess[i]<<"("<<Pro[p].require[i]<<")\t";
else cout <<"\t";
cout<<"\n";
}
}
//////////////////////////////////////
// function Init: user input and Initialize the globe variables
void Init( void ) {
int p,i;
cout<<"Input kind of resources: ";
cin>>nr;
cout<<"Input the total resources:\n";
for ( i=0; i<nr; i++ ) {
cout<<"Resource "<<i+1<<":";
cin>>total[i];
}
cout<<"Input number of process: ";
cin>>np;
cout<<"Input the allocated resources:\n";
for ( p=0; p<np; p++ ) {
cout<<"Process"<<p+1<<" ";
for ( i=0; i<nr; i++ ) {
cout<<"Resource"<<i+1<<":";
cin>>Pro[p].possess[i];
}
}
cout<<"Input the require resources:\n";
for ( p=0; p<np; p++ ) {
cout <<"Process"<<p+1<<" ";
for ( i=0; i<nr; i++ ) {
cout<<"Resource"<<i+1<<":";
cin>>Pro[p].require[i];
}
}
// caculate the free resources
for ( i=0; i<nr; i++ ){
free[i]=total[i];
for ( p=0; p<np; p++ )
free[i]-=Pro[p].possess[i];
}
// initialize the flag
for ( p=0; p<np; p++ )
Pro[p].exist=true;
// initialize the screen
cout << "\nFree \t" <<"\t Resources\n\t";
for ( i=1; i<=np; i++ )
cout <<"P"<< i << "\t";
cout << "\n";
ShowState();
}
///////////////////////////////////////////////////////
///////// function main
void main ( void ) {
bool c; // flag of that at least one process could be finish
int i,tnp;
Init(); // user input
tnp=np; // a temporary variable for number of active process
while ( tnp > 0 ) {
c=false;
for ( i=0; i<np; i++ )
if ( Pro[i].exist )
{
if ( CouldFinish( &Pro[i] ) )
{
Finish ( &Pro[i] );
ShowState();
tnp--;
c=true;
}
}
if ( !c )
{ // no process could be finished. -- deadlock
cout<<"DeadLock!\n";
break;
}
}
}