c++实现银行家算法

计算机操作系统(第三版,汤子瀛编著),按照书上给的5个进程的资源情况写的如下代码。

写的不好, 请不要把我的代码原封不动交给老师。

#include<iostream>
#include<windows.h>
#include<list>
using namespace std;

#define source_num 3
unsigned int id=0;

class Guest{
public:
 Guest(unsigned int (*a)[source_num],unsigned int (*b)[source_num]){
  int i;
  id++;
  ID=id;
  for(i=0;i<source_num;i++)
  {
   allocated[i]=(*a)[i];
   request[i]=(*b)[i];
  }
 }
 unsigned int ID;
 unsigned int allocated[source_num];
 unsigned int request[source_num];

};

class Bank{
public:
 Bank(unsigned int *c){
  int i;
  for(i=0;i<source_num;i++)
  {
   aviable[i]=c[i];
  }
 }
 void test();
 unsigned int aviable[source_num];
 list<Guest> guest;
};

void Bank::test()
{
 int i,flag=0;
 for(list<Guest>::iterator iter=guest.begin();iter!=guest.end();)
 {
  cout<<“进程ID为:”<<iter->ID<<endl;
  cout<<“allocated[“<<source_num<<“]:”;
        for(i=0;i<source_num;i++)
  {
   cout<<iter->allocated[i]<<” “;
  }
  cout<<endl;
  cout<<“request[“<<source_num<<“]:”;
        for(i=0;i<source_num;i++)
  {
   cout<<iter->request[i]<<” “;
   if(iter->request[i]>aviable[i])
   {
    flag=1;
   }
  }
  cout<<endl;
  cout<<“aviable[“<<source_num<<“]:”;
  for(i=0;i<source_num;i++)
  {
            cout<<aviable[i]<<” “;
  }
  cout<<endl;
  if(flag==0)
  {
   Sleep(500);
   cout<<“请求成功,所拥有资源将释放”<<endl<<endl;
            for(i=0;i<source_num;i++)
   {
                aviable[i]+=iter->allocated[i];
    iter->request[i]+=iter->allocated[i];
                iter->allocated[i]=0;
   }
   guest.erase(iter);
   iter=guest.begin();
  }
  else
  {
   flag=0;
   Sleep(500);
   cout<<“请求失败,将会处理下一个进程”<<endl<<endl;
   iter++;
  }
 }
}

int main()
{
 unsigned int a[5][3]={0,1,0,2,0,0,3,0,2,2,1,1,0,0,2};
 unsigned int b[5][3]={7,4,3,1,2,2,6,0,0,0,1,1,4,3,1};
 unsigned int c[3]={3,3,2};
 class Bank bank(c);
 unsigned int (*p)[3],(*q)[3];
 int i,j;
 p=a;q=b;
 for(i=0;i<5;i++)
 {
  class Guest g(p+i,q+i);
        bank.guest.push_back(g);
 }
 bank.test();
 return 0;
}

    原文作者:银行家问题
    原文地址: https://blog.csdn.net/tingyuanss/article/details/8860596
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞