老生常谈的算法,思想很简单,但是实现起来,想跟踪每一步的结果,有点繁琐,详细介绍一下算法的实现过程,也防止自己以后遗忘。编程环境为windows,VC6.0,最古老也是最经典的环境吧。
首先说明几个矩阵,如下所示
#define P 5 //5个任务
#define R 3 //3种资源
int Max[P][R]; //最大需求资源
int Allocation[P][R]; //已分配资源
int Available[R]; //当前可用资源
int Need[P][R]; //任务还需要的资源
其中Max和Allocation是从文件读取,Need是Max-Allocation计算结果,Available是手动输入,初始状态,Max和Allocation的值分别如下:
//max.txt
7 5 3
3 2 2
9 0 2
2 2 2
4 3 3
//allocation.txt
0 1 0
2 0 0
3 0 2
2 1 1
0 0 2
文件读取函数input如下
//从文本中读取数据函数,需要头文件#include <fstream>
void input(FILE* fp, int ptr[P][R])
{
int i,j;
for(i=0; i<P; i++)
{
for(j=0; j<R; j++)
{
fscanf(fp, "%d", &ptr[i][j]);
}
fscanf(fp, "\n");
}
fclose(fp);
}
计算Need矩阵函数
//计算Need矩阵并输出
void computeNeed(int need[P][R], int ptr1[P][R], int ptr2[P][R])
{
int i,j;
for(i=0; i<P; i++)
{
for(j=0; j<R; j++)
{
need[i][j] = ptr1[i][j] - ptr2[i][j];
}
}
cout<<"当前"<<P<<"个任务还需要的资源为:"<<endl;
for(i=0; i<P; i++)
{
cout<<"P("<<i<<"):"<<" ";
for(j=0; j<R; j++)
{
cout<<need[i][j]<<" ";
}
cout<<endl;
}
}
主函数中对于的调用方式为:
#define maxDataPath "E:\\VC6.0_test_program\\BankerAlgorithm\\max.txt"
#define allocationDataPath "E:\\VC6.0_test_program\\BankerAlgorithm\\allocation.txt"
FILE *fpMax = fopen(maxDataPath, "r");
FILE *fpAllocation = fopen(allocationDataPath, "r");
input(fpMax, Max);
cout<<"当前"<<P<<"个任务需要的最大资源为:"<<endl;
output(fpMax, Max);
input(fpAllocation, Allocation);
cout<<"当前"<<P<<"个任务已分配的资源为:"<<endl;
output(fpAllocation, Allocation);
computeNeed(Need, Max, Allocation); //计算Need矩阵并输出
安全性检查函数,其中secure[P][R]矩阵用来保存Available和Need的差值,若secure[i][j] < 0,则当前第j类可用资源小于第i个任务第j类需求资源,计数器+1,一次循环下来,当计数器的值仍然为0时(每个循环开始时计数器会清零),才表示第i个任务满足资源分配要求,返回其下标,否则,返回-1。如下所示
//安全性检查,比较Need和Available,如果有任务处于安全状态,则返回其下标,否则返回-1
int securityCheck(int Allocation[P][R], int Need[P][R], int Available[R])
{
int i,j;
int secure[P][R];
int count[P];
for(i=0; i<P; i++)
{
int c = 0; //计数器清零
cout<<"secure["<<i<<