实验目的:编程实现安全性算法及银行家算法,以帮助深刻理解银行家算法避免死锁的原理。
算法流程图:
实现代码:
#include<iostream>
using namespace std;
const int p = 5; //进程数
const int r = 4; //资源种类
//输入函数
void input(int a[p][r], int b[p][r], int c[p][r], int d[r]) //a-max,b-allocation,c-need,d-available
{
int i, j;
cout << "输入max数据:\n";
for (i = 0; i < p; i++)
for (j = 0; j < r; j++) cin >> a[i][j];
cout << "输入allocation数据:\n";
for (i = 0; i < p; i++)
for (j = 0; j < r; j++) cin >> b[i][j];
cout << "输入need数据:\n";
for (i = 0; i < p; i++)
for (j = 0; j < r; j++) cin >> c[i][j];
cout << "输入available数据:\n";
for (j = 0; j < r; j++) cin >> d[j];
}
//比较函数
int com(int m[r], int n[r]) //比较结果为m中的元素全大于n中的元素返回1,否则返回0
{
int i, flag = 0;
for (i = 0; i < r; i++)
if (m[i] < n[i])
{
flag = 1;
break;
}
if (flag == 1)
return 0;
else
return 1;
}
//安全性检验函数
int stest(int b[p][r], int c[p][r], int d[r])
{
int i, j, k, l, flag = 0;
int need[r], finish[p], work[r];
for (i = 0; i < p; i++)
finish[i] = 0; //finish为1即表示available满足某一进程并让其实现
for (i = 0; i < r; i++)
work[i] = d[i]; //保存数据
cout << "分配序列:\n";
for (k = 0; k < p; k++) //全搜索,直至实现或不可能实现
{
for (i = 0; i < p; i++)
{
if (finish[i] == 1)
continue;
else
{
for (j = 0; j < r; j++)
need[j] = c[i][j];
if (com(work, need))
{
finish[i] = 1;
cout << i + 1 << '\t';
for (l = 0; l < r; l++)
work[l] = work[l] + b[i][l];
break;
}
}
}
}
cout << endl;
for (l = 0; l < p; l++)
{
if (finish[l] == 0)
flag = 1;
}
if (flag == 0)
return 1; //flag为记录finish是否有0存在的标记,当flag=0时,安全
else
return 0;
}
//申请进程后的安全性检验函数
void rtest(int b[p][r], int c[p][r], int d[r], int req[r], int n) //req-request,n-第n个进程申请资源
{
int i, j;
int t[r];
n = n - 1;
for (i = 0; i < r; i++)
t[i] = c[n][i];
if (com(t, req)) //对request和need进行比较
{
if (com(d, req)) //对request和available进行比较
{
for (j = 0; j < r; j++)
{
b[n][j] = b[n][j] + req[j];
c[n][j] = c[n][j] - req[j];
d[j] = d[j] - req[j];
}
if (stest(b, c, d))
cout << "第" << n + 1 << "个进程申请资源成功!\n";
else
{
cout << "第" << n + 1 << "个进程申请资源失败,恢复以前状态。\n";
for (j = 0; j < r; j++)
{
b[n][j] = b[n][j] - req[j];
c[n][j] = c[n][j] + req[j];
d[j] = d[j] + req[j];
}
}
}
else
cout << "进程等待……\n";
}
else
cout << "出错!\n";
}
int main()
{
int j, n; //n-第n个资源申请
int flag1 = 1; //flag1作为循环条件
int max[p][r], allocation[p][r], need[p][r];
int available[r], request[r];
input(max, allocation, need, available);
if (stest(allocation, need, available) == 1)
cout << "初始状态安全!\n\n";
else {
cout << "初始状态不安全,请仔细检查!\n";
return 0;
}
while (flag1)
{
cout << "输入申请资源的进程的序号:\n";
cin >> n;
cout << "输入request数据:\n";
for (j = 0; j < r; j++)
cin >> request[j];
rtest(allocation, need, available, request, n);
cout << "\n继续分配输入1,退出输入0:\n";
cin >> flag1;
}
return 0;
}
验证数据:
运行结果:
说明:
本文章是在原作者的银行家算法文章基础上依据实验课要求修改和完善的,仅供参考,侵权删。