# 银行家算法

bank.h
[code]
#include "windows.h"
#include "time.h"

#define Z 7        //某个墒值
#define M 3        //资源数
#define N 4        //进程数

class CProcess        //进程类
{
public:
CProcess();
void Set();        //设置已分配资源

DWORD max[M], used[M];        //最大需求资源，已分配资源
int ok;        //需求状态标识
};

class CResource        //资源类
{
public:
CResource();

DWORD r[M];        //可利用资源
};

int Test(CProcess p[N]);        //测试是否全部分配结束
int Check(CProcess p[N], CResource r, int n);        //检查是否可分配资源

CProcess::CProcess()
{
srand((unsigned)time (NULL));
Sleep(1000);
for(int i = 0; i < M; i++)
{
max[i] = (rand() % Z) + 1;
used[i] = Z;
cout<<max[i];
}
ok = 0;
cout<<endl;
}

void CProcess::Set()
{
srand((unsigned)time (NULL));
Sleep(1000);
for(int i = 0; i < M; i++)
{
while (used[i] >= max[i])
{
used[i] = rand() % Z;
}
cout<<used[i];
}
cout<<endl;
}

CResource::CResource()
{
srand((unsigned)time (NULL));
cout<<endl;
for(int i = 0; i < M; i++)
{
r[i] = rand() % Z;
cout<<r[i];
}
cout<<endl<<endl;
}

{
for(int i = 0; i < M; i++)
{
r[i] += p.used[i];
p.used[i] = 0;
}
p.ok = 1;
}

int Test(CProcess p[N])
{
int result = 1;
for(int i = 0; i < N; i++)
{
result *= p[i].ok;
}

return result;
}

int Check(CProcess p[N], CResource r, int n)
{
int result = 1;
for(int i = 0; i < M; i++)
{
if (r.r[i] < (p[n].max[i] - p[n].used[i]))
{
return 0;
}
}

return result;
}[/code]
bank.cpp
[code]
#include "iostream.h"
#include "bank.h"

int main(void)
{
CProcess process[N];
CResource resource;
DWORD n = 0, j = 0;

for(int i = 0; i < N; i++)
{
process[i].Set();
}
//    cout<<Test(process);
while (0 == Test(process))
{
//    cout<<"A"<<n;
if (0 == process[n].ok)
{
if (Check(process, resource, n))
{
cout<<(n + 1);
j = 0;

}
}
n++;
j++;
if (j > N)
{
cout<<"no!";
return 1;
}
n %= N;
}

return 0;
}
[/code]

• 本文已收录于以下专栏：

举报原因： 您举报文章：银行家算法 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)