随机算法实现:
#include
int r[3]={3,3,2};//系统拥有的资源 int r0=0,r1=0,r2=0;//记录申请资源 class pcb {
public: int id;
bool state; int max[3]; int alc[3]; int need[3];
pcb() { }
void init() {
state=false; //
cout<<\请输入进程的id,各个资源总需求量和已占用资源\cin>>id;
cout<<\三种资源的最大使用量\cin>>max[0]>>max[1]>>max[2];
cout<<\三种资源的已占有量\ cin>>alc[0]>>alc[1]>>alc[2]; }
int rd(int n) {
return rand()%(n+1); }
int request() {
Sleep(1000);
r0=rd(max[0]-alc[0]); r1=rd(max[1]-alc[1]); r2=rd(max[2]-alc[2]);
cout<<\进程\申请资源a\申请资源b\
申请资源c\
if(r0>r[0]||r1>r[1]||r2>r[2]) {
cout<<\没有那么多资源!!!\ return 0; }
if((r0==(max[0]-alc[0]))&&r1==(max[1]-alc[1])&&r2==(max[2]-alc[2])) {
r[0]=r[0]+alc[0]; r[1]=r[1]+alc[1]; r[2]=r[2]+alc[2]; return 1; }
return 2;
} };
bool safe(vector
int u=r[0]-r0,k=r[1]-r1,l=r[2]-r2; for(int j=i;j int size=temp.size();//记录下容器内还有多少个进程 // int range[size];//记录下队列 int x=0;//计数器 while(!temp.empty()) { static int j=0; if((temp[j].max[0]-temp[j].alc[0])<=u&&(temp[j].max[1]-temp[j].alc[1])<=k&& (temp[j].max[2]-temp[j].alc[2])<=l)//判断是否能运行完 { cout<<\运行%u=u+temp[j].alc[0]; k=k+temp[j].alc[1]; l=l+temp[j].alc[2]; for(int e=j;e temp[e]=temp[e+1]; temp.pop_back(); if(j>=temp.size()) j=0; } else { j++; if(j>=temp.size()) j=0; } x++; if(x==(size*size)) { cout<<\没有安全队列,以上情况不成立\ cout< } return true; } int main() { srand(time(0)); pcb p[5]; vector for(int i=0;i<5;i++) { p[i].init(); vp.push_back(p[i]); } int x=0;//计算器 int c; cout<<\请选择分配资源方法:1.银行家算法 2.随机算法\cin>>c; switch(c) { case 1: while(!vp.empty()) { int a; static int i=0; if((a=vp[i].request())!=0) { if(a==1) { cout<<\进程\已经结束\for(int j=i;j vp[j]=vp[j+1]; } vp.pop_back(); if(i>=vp.size()) i=0; cout<<\资源还剩\资源还剩\资源还剩\ cout< if(safe(vp,i)) { cout<<\存在安全队列\cout< vp[i].alc[0]=vp[i].alc[0]+r0; vp[i].alc[1]=vp[i].alc[1]+r1; vp[i].alc[2]=vp[i].alc[2]+r2; r[0]=r[0]-r0; r[1]=r[1]-r1; r[2]=r[2]-r2; cout<<\资源还剩\b资源还剩\c资源还剩\ cout< if(i>=vp.size()) i=0; } }