东南大学操作系统实验--银行家算法例析.doc
文本预览下载声明
操作系统实验三:银行家算法的实现
一、 基本信息:
a) 实验题目:银行家算法的实现
b) 完成人姓名:韩璐璐
c) 学号d) 报告日期:2016.5.27
二、 实验目的
通过实验,加深对多实例资源分配系统中死锁避免方法——银行家算法的理解,掌握Windows环境下银行家算法的实现方法,同时巩固利用Windows API进行共享数据互斥访问和多线程编程的方法。
三、 实验内容
1. 在Windows操作系统上,利用Win32 API编写多线程应用程序实现银行家算法。
2. 创建n个线程来申请或释放资源,只有保证系统安全,才会批准资源申请。
3. 通过Win32 API提供的信号量机制,实现共享数据的并发访问。
四、程序运行时的初值和运行结果(系统截图)
五、源程序并附上注释
#include iostream
#include time.h
#include vector
#include windows.h
using namespace std;
int r[3] = { 3, 3, 2 };//系统拥有的资源
int r0 = 0, r1 = 0, r2 = 0;//记录申请资源
class pcb
{
public:
int id;
bool state;
int max[3];
int alc[3];
int need[3];
pcb()
{
}
void init()
{
state = false;
cout 请输入进程的id,各个资源总需求量和已占用资源 endl;
cin id;
cout a,b,c三种资源的最大使用量 endl;
cin max[0] max[1] max[2];
cout a,b,c三种资源的已占有量 endl;
cin alc[0] alc[1] alc[2];
}
int rd(int n)
{
return rand() % (n + 1);
}
int request()
{
// Sleep(1000);
r0 = rd(max[0] - alc[0]);
r1 = rd(max[1] - alc[1]);
r2 = rd(max[2] - alc[2]);
cout 进程 id 申请资源a r0 申请资源b r1 申请资源c r2 endl;
if (r0r[0] || r1r[1] || r2r[2])
{
cout 没有那么多资源!!! endl;
return 0;
}
if ((r0 == (max[0] - alc[0])) r1 == (max[1] - alc[1]) r2 == (max[2] - alc[2]))
{
r[0] = r[0] + alc[0];
r[1] = r[1] + alc[1];
r[2] = r[2] + alc[2];
return 1;
}
return 2;
}
};
bool safe(vector pcb temp, int i)
{
int u = r[0] - r0, k = r[1] - r1, l = r[2] - r2;
for (int j = i; jtemp.size() - 1; j++)
temp[j] = temp[j + 1];
temp.pop_back();
int size = temp.size();//记录下容器内还有多少个进程
// int range[size];//记录下队列
int x = 0;//计数器
while (!temp.empty())
{
static int j = 0;
if ((temp[j].max[0] - temp[j].alc[0]) = u (temp[j].max[1] - temp[j].alc[1]) = k
(temp[j].max[2] - temp[j].alc[2]) = l)//判断是否能运行完
{
cout 运行 temp[j].id endl;
u = u + temp[j].alc[0];
k = k + temp[j].alc[1];
l = l + temp[j].alc[2];
for (int e = j; etemp.size() - 1; e++)
temp[e] = temp[e + 1];
temp.pop_back();
if (j = temp.size())
显示全部