学习完操作系统的课程后,我迫不及待地进行了银行家算法的编写。其中银行家算法的编写只需3步;
话不多说,直接进入代码分析。
完整代码如下:
#include<iostream>
#include<assert.h>
using namespace std;
#define num_of_resource 3
#define num_of_binary 5
class OS {
private:
//banker algorithm's datas
int Request[num_of_resource] = { 0, 0,0 };
int binary;
//inherent datas
int Max[num_of_binary][num_of_resource];
int Available[num_of_resource];
int Need[num_of_binary][num_of_resource];
int Allocation[num_of_binary][num_of_resource];
//security check process's datas
bool Finish[num_of_binary] = { false,false,false,false };
int Work[num_of_binary];
bool bl(int* a,int* b,int n) {
int i;
for (i = 0; i < n; i++) {
if (a[i] <= b[i]) continue;
else return false;
}
return true;
}
bool banker_calc() {
assert((binary < num_of_binary) && (binary > 0));
if (!bl(Request, Need[binary], num_of_resource)) return false;
if (bl(Request, Available, num_of_resource)) return false;
for (int i = 0; i < num_of_resource; i++) {
Available[i] -= Request[i];
Allocation[binary][i] += Request[i];
Need[binary][i] -= Request[i];
}
return security_check();
}
bool security_check() {
for (int a = 0; a < num_of_resource; a++) {
Work[a] = Available[a];
}
for (int i = 0; i < num_of_binary; i++) {
if ((Finish[i] == false) && bl(Need[i], Work, num_of_resource)) {
Finish[i] = true;
for (int j = 0; j < num_of_resource; j++) {
Work[j] += Allocation[i][j];
}
i = 0;
}
else return false;
}
return true;
}
public:
OS() {
binary = 0;
cout<<"OS_bin has been created!"<<endl;
}
void setdata(){
cout << "Please input the Max Matrix: "<<endl;
for (int i = 0; i < num_of_binary; i++) {
for (int j = 0; j < num_of_resource; j++) {
cin >> Max[i][j];
}
}
cout << "Please iutput the Allocation Matrix: "<<endl;
for (int i = 0; i < num_of_binary; i++) {
for (int j = 0; j < num_of_resource; j++) {
cin >> Allocation[i][j];
}
}
cout << "Please inout the Available array: "<<endl;
for (int i = 0; i < num_of_resource; i++) {
cin >> Available[i];
}
for (int i = 0; i < num_of_binary; i++) {
for (int j = 0; j < num_of_resource; j++) {
Need[i][j] = Max[i][j] - Allocation[i][j];
}
}
}
void ResourcesApplication() {
cout << "Plesase input the identifier of the binary: "<<endl;
cin >> binary;
cout << endl;
cout << "Please input the number of resources applicated one by one: "<<endl;
for (int i = 0; i < num_of_resource; i++) {
cin >> Request[i];
}
}
bool processApplication() {
if (!security_check()) {
cout << "Try another assignmeng of resources!"<<endl;
return false;
}
ResourcesApplication();
if (banker_calc()) {
cout << "Distribute succeed!" << endl;
return true;
}
else return false;
}
};
int main() {
OS os1;
os1.setdata();
if (os1.processApplication()) {
os1.ResourcesApplication();
os1.processApplication();
}
}```
其中关注OS类的共有函数接口即可。
来源:CSDN
作者:AI wins
链接:https://blog.csdn.net/weixin_44581918/article/details/103246000