#include<iostream>
#include<string>
#include <vector>
using namespace std;
class Resourse
{
public:
string name;
int num;
};
class Progress
{
public:
int id;
int* need;
int* have;
int* Max;
bool flag = false;//未执行完标记
Progress(int n)
{
need = new int[n];
have = new int[n];
Max = new int[n];
}
};
vector<int> safefun(Progress* cpy_pro, int m, vector<Resourse> Ava, int n)
{
int i, j;
int count = 0, lastcount = count;
vector<int> List;
List.resize(m);
fill(List.begin(), List.end(), -1);
for (;;)
{
for (i = 0; i < m; i++)
{
if (!cpy_pro[i].flag)
for (j = 0; j < n; j++)
{
if (Ava[j].num < cpy_pro[i].need[j])//遇到一个资源不满足当前进程,寻找其他进程
{
//if (i == m - 1)//如果最后一个进程还是不满足,则退出
// return List;
break;
}
if (j == n - 1)//该进程可以执行完,可以回收其全部资源
{
cpy_pro[i].flag = true;//标记已处理
lastcount = count;
List[count++] = i;
for (int k = 0; k < n; k++)
{
Ava[k].num += cpy_pro[i].have[k];
}
if (count == m)
return List;
}
}
}
if (lastcount != count)
{
lastcount = count;
}
else return List;
}
return List;
}
int main()
{
vector<Resourse> Available;
int n;
cout << "输入资源种类数:" << endl;
cin >> n;
Available.resize(n);
cout << "输入各资源名称和数量:" << endl;
for (int i = 0; i < Available.size(); i++)
{
cin >> Available[i].name >> Available[i].num;
}
cout << "输入进程个数:" << endl;
int m;
cin >> m;
//auto pro = new Progress(n)[m];
Progress* pro = (Progress*)operator new (sizeof(Progress)* m);
for (int i = 0; i < m; i++)
{
new(&pro[i]) Progress(n);
}
cout << "输入各进程的资源需求情况:" << endl;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
cin >> pro[i].Max[j];
}
cout << "输入当前各进程已分配的资源情况:" << endl;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
cin >> pro[i].have[j];
Available[j].num -= pro[i].have[j];
pro[i].need[j] = pro[i].Max[j] - pro[i].have[j];
}
}
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
cout << pro[i].Max[j] << " ";
}
cout << " ";
for (int j = 0; j < n; j++)
{
cout << pro[i].have[j] << " ";
}
cout << " ";
for (int j = 0; j < n; j++)
{
cout << pro[i].need[j] << " ";
}
cout << endl;
}
cout << "剩余资源:" << endl;
for (auto x : Available)
{
cout << x.name << ":" << x.num << endl;
}
Progress* cpy_pro = (Progress*)malloc(sizeof(Progress)* m);
memcpy(cpy_pro, pro, sizeof(Progress)* m);//复制一份pro对象数组
auto list = safefun(cpy_pro, m, Available, n);
if (list[m - 1] != -1)
{
cout << "存在安全序列:";
for (auto x : list)
{
cout << x << " ";
}
cout << endl;
}
else
cout << "不存在这样的安全序列,不可以这样的初始分配" << endl;
return 0;
}
/*
3
a 10
b 5
c 7
5
7 5 3
3 2 2
9 0 2
2 2 2
4 3 3
0 1 0
2 0 0
3 0 2
2 1 1
0 0 2
*/
银行家算法
最新推荐文章于 2024-07-24 22:46:47 发布