#include
#include
using namespace std;
int Available[10]; //资源向量矩阵
int Max[10][10]; //最大需求矩阵
int Allocation[10][10];//分配矩阵
int Need[10][10]; //需求矩阵
int Request[10]; //请求向量
int process, resource; //进程数、资源种类数
int n; //request申请进程编号
//初始化输入函数
void IniInPut() {
cout << '请输入进程数:';
cin >> process;
cout << '请输入资源种类数:';
cin >> resource;
cout << '请输入最大需求矩阵Max
';
for (int i = 0; i < process; ++i) {
for (int j = 0; j < resource; ++j) {
cin >> Max[i][j];
}
}
cout << '请输入分配矩阵Allocation
';
for (int i = 0; i < process; ++i) {
for (int j = 0; j < resource; ++j) {
cin >> Allocation[i][j];
}
}
cout << '请输入需求矩阵Need
';
for (int i = 0; i < process; ++i) {
for (int j = 0; j < resource; ++j) {
cin >> Need[i][j];
}
}
cout << '请输入资源向量矩阵Available
';
for (int i = 0; i < resource; ++i)
cin >> Available[i];
}
//比较判断函数
bool compare(int a[], int b[]) {
for (int i = 0; i < resource; ++i) {
if (a[i] < b[i])
return false;
}
return true;
}
//安全性检测函数
int stest() {
int Finish[process]; //Finish工作向量
int Work[resource]; //Work工作向量
int flag = 0;
//Finish初始化
for (int i = 0; i < process; ++i) {
Finish[i] = 0;
}
//Work初始化 Work = Available
for (int i = 0; i < process; ++i) {
Work[i] = Available[i];
}
cout << '分配序列:
';
cout << ' allocation need avilable Info' << endl;
for (int i = 0; i < process; ++i) {
for (int j = 0; j < process; ++j) {
if (Finish[j] == 1) {
continue;
} else {
if (compare(Work, Need[j])) {
Finish[i] = 1;
flag = 1;
cout << '进程' << j+1;
cout << setw(9);
for (int x = 0; x < resource; ++x) {
cout << Allocation[j][x] << setw(4);
}
cout << setw(11);
for (int x = 0; x < resource; ++x) {
cout << Need[j][x] << setw(4);
}
cout << setw(11);
for (int x = 0; x < resource; ++x) {
cout << Work[x] + Allocation[j][x] << setw(4);
}
cout << setw(18) << 'True' << endl;
//进程完成,释放资源
for (int y = 0; y < resource; ++y) {
Work[y] += Allocation[j][y];
}
break;
}
}
if (flag) {
break;
}
}
}
for (int i = 0; i < process; ++i) {
if (Finish[i] == 0)
return 0; //不存在安全序列
}
return 1; //存在安全序列
}
//请求安全性检测函数
void rtest(int n){
if(compare(Available,Request)&&compare(Need[n-1],Request))//当available>=request 并且 need >=request时可分配
{
for(int i=0;i<resource;++i){//试分配
Allocation[n-1][i]+=Request[i];
Need[n-1][i]-=Request[i];
Available[i]-=Request[i];
}
if(stest())
cout << '允许'<<n<<'进程申请资源'<<endl;
else{
cout << '不允许'<<n<<'进程申请资源'<<endl;
for(int i=0;i<resource;++i){//试分配失败,恢复资源
Allocation[n-1][i]-=Request[i];
Need[n-1][i]+=Request[i];
Available[i]+=Request[i];
}
}
}
else
cout << '申请资源数越界,无法分配'<<endl;
}
int main() {
IniInPut();
if (stest() == 1) {
cout << '存在安全序列' << endl;
} else
cout << '不存在安全序列' << endl;
cout << '请输入发出请求向量request的进程编号:'<<endl;
cin >> n;
cout << '请输入请求向量request:'<<endl;
for(int i=0;i<resource;++i){
cin>>Request[i];
}
rtest(n);
return 0;