首页 > 编程语言 >银行家算法

银行家算法

时间:2022-10-18 15:46:40浏览次数:37  
标签:available cout int 算法 tempP need plist 银行家

#include <iostream>
#include <vector>
#include <string>
	

using namespace std;

typedef struct{
	int A;
	int B;
	int C;
}MAX,ALLOCATION,NEED,AVAILABLE,WORK;

class PCB{
public:
	 MAX maxs;
	 ALLOCATION allocation; 
	 NEED need;
	 WORK work;
	 string pname;
	 bool finish;
	 PCB(){}
	 PCB(string paname,MAX maxs,ALLOCATION allocation,NEED need):pname(pname),maxs(maxs),allocation(allocation),need(need){}
	 bool runState(AVAILABLE a){
		 return need.A < a.A && need.B < a.B && need.C < a.C;
	 }
	 void show(){
		cout << "线程名:" << pname<< " \t MAX " << maxs.A<< " " << maxs.B<< " " << maxs.C<< 
			" \t ALLOCATION " << allocation.A<< " " << allocation.B<< " " << allocation.C<< 
			" \t NEED " << need.A<< " " << need.B<< " " << need.C << " finish:" <<(finish?"ture":"false")<< endl;
	 }
};

bool Request(PCB &pcb,AVAILABLE &available){
	// 判断是否可执行
	if(pcb.runState(available)){
		pcb.work = available;
		available.A+=pcb.allocation.A;
		available.B+=pcb.allocation.B;
		available.C+=pcb.allocation.C;
		pcb.finish=true;
		return true;
	}else return false;
}
void RunP(vector<PCB> &plist,AVAILABLE &available){
	int cout = 1; // 进程运行完成总数
	int non = 1;
	vector<PCB> saveQueue;
	while(non < plist.size() && cout < plist.size() ){ // 当 non 等于 线程数,则说明无法执行
		for(int i = 0; i < plist.size(); i ++)
		{
			// 判断是否能执行
			if(Request(plist[i],available)){
				saveQueue.push_back(plist[i]);
				cout++;
			}else non++; // 如果没执行,则non加1
		}
	}
	// 如果相等则为运行成功,如果不相等,则是死锁
	if(cout == plist.size()){
		printf("运行成功 系统此时状态安全 安全序列为(");
		for(int i = 0; i < saveQueue.size(); i ++)
		{
			printf("%s",saveQueue[i].pname.c_str());
			if(i != saveQueue.size()-1) printf(",");
		}
		printf(")\n");
	}else {
		printf("运行失败,进程: %s 无法执行");
	}
	
}

int main(){

	// 初始化进程序列
	int n;
	cout <<"请输入进程个数:";
	cin >> n;

	AVAILABLE available;
	cout <<"请输入ABC的资源数(如: 1 3 4):";
	cin >> available.A >> available.B >> available.C;
	printf("AVAILABLE: A=%d B=%d C=%d \n", available.A , available.B, available.C);
	vector<PCB> plist;
	for(int i = 0; i < n;i++){
		PCB tempP;
		cout << "请输入线程名\t MAX A B C \t ALLOCATION A B C \t NEED A B C" << endl;
		printf( "如: P1 1 2 3 1 2 3 1 2 3\n");
		cin
			>>tempP.pname>>tempP.maxs.A>>tempP.maxs.B>>tempP.maxs.C>>
			tempP.allocation.A>>tempP.allocation.B>>tempP.allocation.C
			>>tempP.need.A>>tempP.need.B>>tempP.need.C;
		tempP.show();
		plist.push_back(tempP);
	}
	

	return 0;
}

标签:available,cout,int,算法,tempP,need,plist,银行家
From: https://www.cnblogs.com/pphboy/p/16802771.html

相关文章