用c++写一个银行家算法代码
时间: 2024-01-27 17:03:50 浏览: 60
用C++写的银行家算法
4星 · 用户满意度95%
以下是一个简单的 C++ 实现银行家算法的代码:
```
#include<iostream>
using namespace std;
int main()
{
int n, m;
cout << "Enter the number of processes: ";
cin >> n;
cout << "Enter the number of resources: ";
cin >> m;
int allocated[n][m], maximum[n][m], available[m];
cout << "Enter the allocated resources for each process:\n";
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
cin >> allocated[i][j];
cout << "Enter the maximum resources for each process:\n";
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
cin >> maximum[i][j];
cout << "Enter the available resources: \n";
for(int i = 0; i < m; i++)
cin >> available[i];
int need[n][m];
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
need[i][j] = maximum[i][j] - allocated[i][j];
bool finish[n] = {0};
int safe_sequence[n], work[m];
for(int i = 0; i < m; i++)
work[i] = available[i];
int count = 0;
while(count < n)
{
bool found = false;
for(int i = 0; i < n; i++)
{
if(finish[i] == 0)
{
int j;
for(j = 0; j < m; j++)
if(need[i][j] > work[j])
break;
if(j == m)
{
for(int k = 0; k < m; k++)
work[k] += allocated[i][k];
safe_sequence[count++] = i;
finish[i] = 1;
found = true;
}
}
}
if(found == false)
{
cout << "System is not in safe state.";
return 0;
}
}
cout << "Safe sequence is: ";
for(int i = 0; i < n; i++)
cout << safe_sequence[i] << " ";
return 0;
}
```
这段代码实现了银行家算法的主要逻辑。用户需要输入进程数、资源数、每个进程的已分配和最大需求资源数以及可用资源数,然后程序会计算出每个进程的需求资源数和安全序列,并输出到屏幕上。注意,以上代码仅作为演示用途,实际环境中需要加入更多的安全检查和错误处理。
阅读全文