您好,欢迎来到五一七教育网。
搜索
您的当前位置:首页c++通过银行家算法检查安全性,并输出安全序列

c++通过银行家算法检查安全性,并输出安全序列

来源:五一七教育网

在主函数中,我们首先调用 getInput() 函数获取输入数据,然后调用 displayNeed() 函数显示还需要的矩阵。


接下来,我们调用 isSafe() 函数判断系统是否处于安全状态,并输出安全序列。


在 isSafe() 函数中,我们采用了贪心的策略:依次处理每个进程,如果发现某个进程能够在当前可用资源下完成任务,则把它加入安全序列中,并把它的占用资源释放给系统。然后重新开始处理进程序列。


如果所有进程都能被加入安全序列中,说明系统处于安全状态,返回 true。否则说明系统处于不安全状态,返回 false。


在输出安全序列时,我们遍历 safeSeq 向量,并依次输出其中的元素,即为安全序列。


按以上方式实现银行家算法的C++代码可以输出一个安全序列。

 

#include <iostream>
#include <vector>

using namespace std;

const int N = 10;
int n, m; // 进程数和资源数
int available[N]; // 可用资源数
int allocation[N][N]; // 已分配矩阵
int max_req[N][N]; // 最大需求矩阵
int need[N][N]; // 还需要的矩阵
bool finish[N]; // 记录进程是否完成
vector<int> safeSeq; // 安全序列

void getInput()
{
    cout << "Enter number of processes: ";
    cin >> n;
    cout << "Enter number of resources: ";
    cin >> m;

    cout << "Enter available resources: ";
    for (int i = 0; i < m; i++) {
        cin >> available[i];
    }

    for (int i = 0; i < n; i++) {
        cout << "Enter maximum resources for process " << i << ": ";
        for (int j = 0; j < m; j++) {
            cin >> max_req[i][j];
        }
    }

    for (int i = 0; i < n; i++) {
        cout << "Enter resources allocated to process " << i << ": ";
        for (int j = 0; j < m; j++) {
            cin >> allocation[i][j];
            need[i][j] = max_req[i][j] - allocation[i][j];
        }
        finish[i] = false;
    }
}

bool isSafe()
{
    int work[m];
    for (int i = 0; i < m; i++) {
        work[i] = available[i];
    }

    for (int i = 0; i < n; i++) {
        if (finish[i]) continue;

        bool canFinish = true;
        for (int j = 0; j < m; j++) {
            if (need[i][j] > work[j]) {
                canFinish = false;
                break;
            }
        }

        if (canFinish) {
            for (int j = 0; j < m; j++) {
                work[j] += allocation[i][j];
            }
            finish[i] = true;
            safeSeq.push_back(i);
            i = -1;
        }
    }

    for (int i = 0; i < n; i++) {
        if (!finish[i]) {
            return false;
        }
    }

    return true;
}

int main()
{
    getInput();

    displayNeed();

    if (isSafe()) {
        cout << "System is in safe state." << endl;
        cout << "Safe sequence is: ";
        for (int i = 0; i < n; i++) {
            cout << safeSeq[i] << " ";
        }
        cout << endl;
    } else {
        cout << "System is in unsafe state." << endl;
    }

    return 0;
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 517ttc.cn 版权所有 赣ICP备2024042791号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务