银行家算法
银行家算法主要用于避免死锁。原理是进行资源分配之前先计算资源分配的安全性,分配不会导致系统进入不安全状态,则将资源分配给进程。否则让进程等待。注意该算法的核心是安全性的判断:可以理解成一个闯关游戏,若主角的攻击力、防御力、(剩余资源数量)全部都高于某个敌人对应的攻击力、防御力(对应的请求资源的数量), 则主角可以打败这个怪兽并全部获取怪兽的属性(分配和回收资源),若主角可以在这个规则下打败全部的怪兽,则这样的情况下是安全状态。
下图为本算法的基本流程图:
/*
Banker's Algorithm
2019-11-10
input data format:
====================
process_number source_number
s1_avl s2_avl s3_avl...
p1_s1_max p1_s2_max p1_s3_max... p1_s1_alc p1_s2_alc p1_s3_alc...
p2_s1_max p2_s2_max p2_s3_max... p2_s1_alc p2_s2_alc p2_s3_alc...
p3_s1_max p3_s2_max p3_s3_max... p3_s1_alc p3_s2_alc p3_s3_alc...
...
process_id s1_req s2_req s3_req...
...
====================
*/
#include<stdio.h>
#include<string.h>
#include<vector>
#include<string>
#include<iostream>
using namespace std;
typedef vector<int> array;
typedef vector<int> arrays[100];
array Available, Finish, Request;
arrays Max, Allocation, Need;
int ProNum, SoureNum; //process number and source number;
int Running; //the munber of process that still running
int Pid; //the id of process that request source
void testPrintf();
int getData();
void initNeed();
void updateNeed();
void initData();
int safetyCheck();
void getRequest();
int Satifycheck();
bool IsSatisfy();
int main(){
//get input data and printf if input accepted
if (getData() == 0){
printf("Get data success: \n");
testPrintf();
}
else{
printf("Get data fail, exit!");
return 0;
}
//check if safe before recevie a requestment
printf("First check: ");
if (safetyCheck() < 0){
printf("The system is unsafe!\n");
return 0;
}
else{
printf("The system is safe, begin to receive requestment! \n\n");
}
//receive request of process and handle it
Running = ProNum;
while (Running != 0){
getRequest();
//check if owned source is enough to give to the process
if (!IsSatisfy()){
printf("Source not enough, It process need to block!\n");
testPrintf();
continue;
}
//give those source to process
for (int i