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

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

#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;

}

LeaveCriticalSection (&cs) ;

}

string print(Philosopher *pA)

{

//pA->Change();

int i=pA->getinfo();

string str;

if(i==0)

str="等待";

else if(i==1)

str="就餐";

else str="思考";

return str;

}

string toolstatus(bool a)

{

string state;

if(a==true)

state="闲";

if(a==false)

state="用";

return state;

}

int main()

{

char con='y'; //判断是否继续

// con = 'n';

for(int i=0;i<5;i++)

tools[i]=true; //筷子都未使用,初始化

Philosopher P1(1),P2(2),P3(3),P4(4),P5(5);

InitializeCriticalSection (&cs) ; //初始化初始化临界区

cout<<"-----------------------状态说明示意图:-----------------------"<

cout<<" 筷子0的状态"<<" "<<"筷子1的状态"<

cout<<"哲学家5号的状态"<<" "<<"哲学家2号的状态"<

cout<<" 筷子4的状态"<<" "<<"筷子2的状态"<

cout<<" 哲学家4号的状态"<<" "<<"哲学家3号的状态"<

cout<<" "<<"筷子3的状态"<

//cout<<" "<<"哲学家3号的状态"<<" "<

cout<<"筷子的状态,用表示使用中,闲表示空闲中。"<

cout<<"--------------------------------------------------------------"<

//cout<<"当前状态:";

cout<

//cin>>con;

while(con=='y')

相关文档
最新文档