问题描述
- C++ 关于哲学家进餐问题求教??
-
#include<Windows.h> #include<iostream> #include<string> #include<thread> #include<mutex> using namespace std; std::mutex mu; std::mutex chopsticks[5]; const char THINKING = 0; const char WAITING = 1; const char EATING = 2; class philosopher { public: philosopher(int n) { status = THINKING; number = n; } ~philosopher() { }; int can_eat() { philosopher left = philosopher((number + 1) % 5); philosopher right = philosopher((number + 4) % 5); if (left.get_status() != EATING && right.get_status() != EATING && status==WAITING) return 1; return 0; } void eat() { chopsticks[number % 5].lock(); chopsticks[(number + 1) % 5].lock(); status = EATING; Sleep(1000); } void put_down_chopsticks() { status = THINKING; chopsticks[number % 5].unlock(); chopsticks[(number + 1) % 5].unlock(); } int get_status() { return status; } int get_number() { return number; } void set_status(int s) { status = s; } private: int status; int number; }; philosopher* ph_1 = new philosopher(0); philosopher* ph_2 = new philosopher(1); philosopher* ph_3 = new philosopher(2); philosopher* ph_4 = new philosopher(3); philosopher* ph_5 = new philosopher(4); void show() { mu.lock(); cout << "===============" << endl; cout << ph_1->get_number() << ":" << ph_1->get_status() << endl; cout << ph_2->get_number() << ":" << ph_2->get_status() << endl; cout << ph_3->get_number() << ":" << ph_3->get_status() << endl; cout << ph_4->get_number() << ":" << ph_4->get_status() << endl; cout << ph_5->get_number() << ":" << ph_5->get_status() << endl; mu.unlock(); } void try_to_eat(philosopher *p) { while (1) { switch (p->get_status()) { case THINKING: Sleep(2000); p->set_status(WAITING); break; case WAITING: if (p->can_eat()) { p->eat(); } else{ p->set_status(WAITING); } break; case EATING: p->put_down_chopsticks(); break; default: break; } show(); } } int main() { std::thread t1(try_to_eat, ph_1); std::thread t2(try_to_eat, ph_2); std::thread t3(try_to_eat, ph_3); std::thread t4(try_to_eat, ph_4); std::thread t5(try_to_eat, ph_5); show(); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); return 0; }
解决方案
操作系统并发和互斥:哲学家进餐问题和理发师问题?
1. 哲学家进餐问题:?
(1) 在什么情况下5 个哲学家全部吃不上饭??
考虑两种实现的方式,如下:?
A.?
算法描述:?
void philosopher(int i) /*i:哲学家编号,从0 到4*/?
{?
while (TRUE) {?
think( ); /*哲学家正在思考*/?
take_fork(i)......
答案就在这里:关于哲学家进餐问题
解决方案二:
你想问的问题呢?这段程序有什么不对吗?
时间: 2024-09-16 00:17:46