东南大学操作系统实验报告--银行家算法

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

操作系统实验三:银行家算法的实现

一、基本信息:

a)实验题目:银行家算法的实现

b)完成人姓名:韩璐璐

c)学号:71114115

d)报告日期:2016.5.27

二、实验目的

通过实验,加深对多实例资源分配系统中死锁避免方法——银行家算法的理解,掌握Windows环境下银行家算法的实现方法,同时巩固利用

Windows API进行共享数据互斥访问和多线程编程的方法。

三、实验内容

1. 在Windows操作系统上,利用Win32 API编写多线程应用程序实现银行家算法。

2. 创建n个线程来申请或释放资源,只有保证系统安全,才会批准资源申请。

3. 通过Win32 API提供的信号量机制,实现共享数据的并发访问。

四、程序运行时的初值和运行结果(系统截图)

五、源程序并附上注释#include #include #include

#include

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 (r0>r[0] || r1>r[1] || r2>r[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 temp, int i)

{

int u = r[0] - r0, k = r[1] - r1, l = r[2] - r2;

for (int j = i; 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; e

temp[e] = temp[e + 1];

temp.pop_back();

if (j >= temp.size())

j = 0;

}

else

{

j++;

if (j >= temp.size())

j = 0;

}

x++;

if (x == (size*size))

{

cout << "没有安全队列,以上情况不成立" << endl;

cout << endl;

return false;

}

}

return true;

}

相关文档
最新文档