操作系统哲学家就餐问题实验报告

操作系统哲学家就餐问题实验报告
操作系统哲学家就餐问题实验报告

图3.返回哲学家状态流程图

图4返回餐具状态模块流程图

3)数据结构

(1)、定义一个哲学家类,包含两个私有对象和四个公有对象。

(2)、定义函数:

Number对象:哲学家的编号;

Status对象:保存当前该哲学家的状态,0表示等待,1表示吃饭,2表示思考;

Philosopher(int num)方法:哲学家类构造函数,参数num表示哲学家编号;find() const方法:返回该哲学家编号;

getinfo() const方法:返回哲学家当前状态;

Change()方法:根据题目要求改变哲学家的状态(等待->进餐->思考)

另外,程序中包含一个公有对象,bool类型数组tools[6],用来保存6把餐具当前状态:true表示该餐具当前空闲,false表示该餐具当前正被使用。

程序中还包含两个公有函数:print和toolstatus。Print用来返回一个哲学家的状态,toolstatus用来返回一个餐具的状态。

4)实现步骤

1)打开VC,选择菜单项File->New,选择Projects选项卡并建立一个名为xwj 的win32 console application工程,创建时注意指定创建该工程的目录;

(2)在工程中创建源文件xwj.cpp:选择菜单项Project->Add to project->Files,此时将打开一个新窗口,在其中的“文件名”输入栏中输入自己想要创建的文件名,这里是xwj.cpp;接着询问是否创建新文件时回答“yes”。通过Workspace->Source Files打开该文件,在其中编辑源文件并保存;

(3)通过调用菜单项Build->Rebuild all进行编译连接,可以在指定的工程目录下得到debug->xwj.exe程序。

5、实验测试及分析:

图5.测试结果1

图7.测试结果3

#include

#include

#include

#include

#include

using namespace std;

bool tools[5]; //全局变量,用餐工具

CRITICAL_SECTION cs; //信号量, 在线程中使用,临界区

class Philosopher

{

private:

int number;

int status; /*标记当前哲学家的状态,0表示正在等待

(即处于饥饿状态),1表示得到两支筷子正在吃饭,2表示正在思考*/ public:

Philosopher(int num=0): status(2), number(num) { }

const int find()

{

return number;

}

const int getinfo()

{ return status; }

void Change() ; //状态改变函数

void dead_lock();

};

/////////

void Philosopher::dead_lock()

{

EnterCriticalSection (&cs) ; //进入临界区

string s;

if(status==1)

{

tools[number%5]=true;

// tools[(number-1)%5]=true;

status=2;

}

else if(status==2)

{

status=0;

//tools[(number-1)%5]=false;

//tools[(number-1)%5]=true;

}

else if(status==0)

{

tools[number%5]=false;

tools[(number-1)%5]=false;

status=1;

}

LeaveCriticalSection (&cs) ;

// cout<<"*********";

}

/////////

void Philosopher::Change()

{

EnterCriticalSection (&cs) ; //进入临界区

if(status==1) //正在进餐

{

tools[number%5]=true; //放下左手工具

tools[(number-1)%5]=true; //放下右手工具

status=2; //改变状态为思考

}

else if(status==2) //思考中

{

status=0; //改变状态为等待

}

else if(status==0) //等待中

{

if(tools[number%5]&&tools[(number-1)%5]) //左右手两边工具均为空闲状态

{

tools[number%5]=false; //拿起左手工具

tools[(number-1)%5]=false; //拿起右手工具

status=1;

}

}

相关主题
相关文档
最新文档