银行家算法
#include <iostream>
using namespace std;
int Available[3] = {3,3,2};
int Max[5][3] = { {7,5,3}, {3,2,2}, {9,0,2}, {2,2,2}, {4,3,3} };
int Allocation[5][3] = { {0,1,0} ,{2,0,0}, {3,0,2} ,{2,1,1} ,{0,0,2} };
int Need[5][3] = { {7,4,3} ,{1,2,2} ,{6,0,0} ,{0,1,1} ,{4,3,1} };
int Request[50][100];
int Finish[5];
int p[50];
int m=5, n=3;
int Safe()
{
int i, j, l = 0;
int Work[100];
for (i = 0; i < n; i++)
Work[i] = Available[i];
for (i = 0; i < m; i++)
Finish[i] = 0;
for (i = 0; i < m; i++)
{
if (Finish[i] == 1)
continue;
else
{
for (j = 0; j < n; j++)
{
if (Need[i][j] > Work[j])
break;
}
if (j == n)
{
Finish[i] = 1;
for (int k = 0; k < n; k++)
Work[k] = Work[k] + Allocation[i][k];
p[l++] = i;
i = -1;
}
else continue;
}
if (l == m)
{
cout << "系统是安全的" << '\n';
cout << "系统安全序列是:\n";
for (i = 0; i < l; i++)
{
cout << p[i];
if (i != l - 1)
cout << "-->";
}
cout << '\n';
return 1;
}
}
return 0;
}
int main()
{
int i, j, mi;
bool b = true;
Safe();
while (1)
{
cout << "目前已分配资源:"<<endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cout << Allocation[i][j] << " ";
}
cout << endl;
}
cout << "进程还需资源数:"<<endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cout << Need[i][j] << " ";
}
cout << endl;
}
cout << "各个资源还可利用资源数:"<<endl;
for (int i = 0; i < n; i++) {
cout << Available[i] << " ";
}
cout << endl;
cout << "输入要申请的资源的进程号;\n";
cin >> mi;
cout << "输入进程所请求的各个资源的数量\n";
for (i = 0; i < n; i++)
cin >> Request[mi][i];
for (i = 0; i < n; i++)
{
if (Request[mi][i] > Need[mi][i])
{
cout << "所请求资源数超过进程的需求量!\n";
b = false;
break;
}
if (Request[mi][i] > Available[i])
{
cout << "所请求资源数超过系统所有的资源数!\n";
b = false;
break;
}
}
if (b) {
for (i = 0; i < n; i++)
{
Available[i] = Available[i] - Request[mi][i];
Allocation[mi][i] = Allocation[mi][i] + Request[mi][i];
Need[mi][i] = Need[mi][i] - Request[mi][i];
}
if (Safe())
cout << "同意分配请求\n";
else
{
cout << "对不起.你的请求被拒绝…\n";
for (i = 0; i < n; i++)
{
Available[i] = Available[i] + Request[mi][i];
Allocation[mi][i] = Allocation[mi][i] - Request[mi][i];
Need[mi][i] = Need[mi][i] + Request[mi][i];
}
}
for (i = 0; i < m; i++)
Finish[i] = 0;
}
}
return 0;
}