银行家算法

来源:互联网 发布:数据安全保密制度 编辑:程序博客网 时间:2024/06/06 16:30
#include<cstdio>
#include<iostream>
#define M 30//资源
#define N 20//进程
using namespace std;
int n;//进程的个数
int m;//资源的种类数
int wp;//所要请求资源的进程
int Wp[M];//请求各个资源的值
int process_end[N];//判断是否是已经运行过的进程
int tage[N];//记录进程运行的次序
int Max[N][M];//进程所最大资源值
int Need[N][M];//进程所需要的资源
int All[N][M];///进程已有的资源
int Resources[M];//还可以利用的资源数  


int isok(int k)
{
    int ok=1;
    for(int i=0;i<m&&ok;++i)
    {
        if(Need[k][i]>Resources[i])
        {
            ok=0;
        }
    }
    return ok;
}


void chushi()
{
    cout<<"进程已有的资源 "<<endl;
    for(int i=0;i<n;++i)
    {
    for(int j=0;j<m;++j)
    {
        cin>>All[i][j];
    }
    }
    cout<<"进程所最大资源值"<<endl;
    for(int i=0;i<n;++i)
    {
        for(int j=0;j<m;++j)
    {
    cin>>Max[i][j];
    Need[i][j]=Max[i][j]-All[i][j];
    }
    }
    cout<<"每个资源所能够被利用的值 "<<endl;
    for(int i=0;i<m;++i)
    {
        cin>>Resources[i];
    }

}


int safe()//检查是否安全
{
    int k=0;
    int p=1;
    int ok=1;
    while(k<n&&ok)
    {
        int i;
        p=1;
        for(i=0;i<n&&p;++i)
        {
            if((process_end[i]==0)&&isok(i))
            {
            tage[k]=i;
            k++;
            process_end[i]=1;
            for(int j=0;j<m;++j)
            {
            Resources[j]+=All[i][j];
            }
            p=0;
            }
        }
        if(p)
        {
            ok=0;
        }
    
    }
    return ok;

}
void bank()
{
    int ok=1;
    for(int i=0;i<m&&ok;++i)
    {
        if(Wp[i]>Need[wp][i])
        {
            ok=0;
            cout<<"请求失败!"<<endl;
        }
    }
    if(ok)
    {
        for(int i=0;i<m&&ok;++i)
        {
            if(Wp[i]>Resources[i])
            {
                ok=0;
                cout<<"请求失败!"<<endl;
            }
        }
        if(ok)
        {
            for(int i=0;i<m;++i)
            {
                All[wp][i]+=Wp[i];
                Need[wp][i]-=Wp[i];
                Resources[i]-=Wp[i];
            }
            if(safe())
            {
                cout<<"请求成功!"<<endl;
            }
            else
            {
                cout<<"请求失败!"<<endl;
            }
        }
    }
}
int main()
{
    int j;
    cout<<"进程个数:"<<endl;
    cin>>n;
    cout<<"资源种类:"<<endl;
    cin>>m;
    chushi();
    cout<<"1-检查是否安全 2-请求资源"<<endl;
    cin>>j;
    if(j==1)
    {
        if(safe())
        {
            cout<<"安全"<<endl;
            cout<<"安全序列可以是: ";
            for(int i=0;i<n-1;++i)
            {
                cout<<tage[i]<<"->";
            }
            cout<<tage[n-1]<<endl;
        }
        else
        {
            cout<<"死锁"<<endl;
        }
    }
    else
    {
        cout<<"请求资源的进程"<<endl;
        cin>>wp;
        cout<<"请求的各个资源的值"<<endl;
        for(int i=0;i<m;++i)
        {
            cin>>Wp[i];
        }
        bank();
    }
    return 0;
}