#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<<\"-----------------------状态说明示意图:-----------------------\"< P1.Change(); P2.Change(); P3.Change(); P4.Change(); P5.Change(); cout<<\"当前状态为:\"< cin>>con; Sleep(20); } while(con=='n') { P1.dead_lock(); P2.dead_lock(); P3.dead_lock(); P4.dead_lock(); P5.dead_lock(); cout<<\"死锁情况\"< DeleteCriticalSection (&cs) ; // return 0; } 退出资源区 因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- xiaozhentang.com 版权所有 湘ICP备2023022495号-4
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务