#include
using namespace std;
int kind;//进程种类
int num;//所有种类的资源数
int *Avalible;//每个资源对应的可以获取的资源数的数组指针
int **Allocation;//已经分配的资源二维矩阵的指针,其中行数代表进程,列数代表该进程持有的某种资源
int **Need;//需求数组,即每个进程对应于某个资源的需求量的二维指针
int locknum;//记录不能完成的进程数
void init(int kind, int num){ //初始化进程
Avalible = new int[kind];
cout << "请输入各个种类可利用的资源数:" << endl;
for (int i = 0; i < num;i++){
cin >> Avalible[i];
}
Allocation = new int*[kind]; //二维数组初始化
for (int i = 0; i < kind; i++){
Allocation[i] = new int[num];
}
cout << "请输入各个进程分别持有的资源的数目:" << endl;
for (int i = 0; i < kind;i++) //二维数组赋初值,资源分配矩阵
for (int j = 0; j < num; j++)
cin >> Allocation[i][j];
Need = new int*[kind]; //二维数组初始化
for (int i = 0; i < kind; i++){
Need[i] = new int[num];
}
cout << "请输入各个进程对于各个资源的需求数目:" << endl;
for (int i = 0; i < kind; i++) //二维数组赋初值,还需要资源矩阵
for (int j = 0; j < num; j++)
cin >> Need[i][j];
}
bool safety(){
int i, j;
int sign = 0;//作为序列的引导
int *work = new int[kind]; //代替用数组,以免出错
int *safe = new int[kind]; //资源分配数组
bool *visit = new bool[kind]; //标记访问数组
for (int i = 0; i < kind; i++) //访问数组初始化
visit[i] = false;
for (int i = 0; i < kind; i++) //工作数组初始化
work[i] = Avalible[i];
for (i = 0; i < kind; i++){
if (visit[i] == false){ //未被访问的进程进行访问
for (j = 0; j < num; j++){
if (Need[i][j]>work[j])break;
}
if (j == num){ //如果这个进程可以被分配资源,并完成该进程
visit[i] = true;
for (int k = 0; k < num; k++) //该进程完成后将资源释放回系统
work[k] += Allocation[i][k];
safe[sign++] = i; //记录进程访问序列
i = -1; //系统资源更新,重新开始扫描进程
}
}
}
locknum = 0;
for (int k = 0; k < kind; k++){ //循环记录下不能满足的进程数
if (visit[k] == false)
locknum++;
}
if (locknum == 0){
cout << "存在安全序列:(进程释放顺序)" << endl;
for (int k = 0; k < kind; k++)
cout << safe[k] << " ";
cout << endl;
return true;
}
else if (locknum == kind){
cout << "所有进程都不能结束,死锁" << endl;
}
else cout << "系统处于不安全状态" << endl;
delete work,safe,visit;
return false;
}
void allocate(){
int *request=new int[num];
int process; //记录请求获取资源的进程数
cout << "请输入准备获取资源的进程序号:" << endl;
cin >> process;
cout << "输入该进程准备请求的各种累资源的数目:" << endl;
for (int i = 0; i < kind; i++)
cin >> request[i];
for (int i = 0; i
if (request[i]>Need[process][i]){
cout << "申请的资源大于需要的资源,申请输入错误!" << endl; return;
}
else if (request[i]>Avalible[i])
{
cout << "系统中无足够的资源满足进程的申请,系统不予分配资源!" << endl; return;
}
}
for (int i = 0; i
{
Avalible[i] -= request[i];
Need[process][i] -= request[i];
Allocation[process][i] += request[i];
}
if (safety())
{
cout << "系统可以为该进程分配资源\n"; return;
}
else
{
cout << "系统不为该进程分配资源\n"; return;
}
}
int main()
{
cout << "请输入进程的数目:" << endl;
cin >> kind;
cout << "请输入资源的种类:" << endl;
cin >> num;
init(kind,num);
safety();
while (true){
allocate();
}