操作系统经典同步互斥问题——哲学家就餐
2014-10-04 16:46
411 查看
仅仅允许4个人同时就餐
#include <iostream> #include <mutex> #include <cstdio> #include <thread> #include <semaphore.h> using namespace std; #define THINK(i) printf("ph[%d] is thinking...\n", i) #define EAT(i) printf("ph[%d] eats.\n", i) void P(mutex &mt) { mt.lock(); } void V(mutex &mt) { mt.unlock(); } void P(sem_t* sem) { if(sem_wait(sem)) perror("P error!"); } void V(sem_t* sem) { if(sem_post(sem)) perror("V error!"); } // 加入unistd.h出现问题,似乎与thread的兼容性比较差,于是重写 void delay() { int sum=0; for(int i = 0; i < 10000000; i++) sum += i; } mutex fork[5]; sem_t room; void init() { sem_init(&room, 0, 4); } void philosopher (int i) { for(int j = 0; j < 5; j++) { THINK(i); P(&room); P(fork[i]); P(fork[(i+1)%5]); EAT(i); V(&room); V(fork[i]); V(fork[(i+1)%5]); } } int main() { init(); thread t[] = { thread(philosopher, 0), thread(philosopher, 1), thread(philosopher, 2), thread(philosopher, 3), thread(philosopher, 4), }; for(int k = 0; k < 5; k++) t[k].join(); return 0; }
相关文章推荐
- 操作系统经典同步互斥问题——哲学家就餐
- 三个同步与互斥问题之哲学家就餐
- 进程的同步与互斥-哲学家问题
- 操作系统哲学家就餐问题——定义一个互斥信号量mutex
- 经典同步问题(二)---哲学家就餐问题
- IPC----哲学家就餐问题(并发与互斥)
- 进程同步的经典问题2——哲学家就餐问题
- uc笔记12---竞争与同步,互斥量,信号量,死锁,条件变量,哲学家就餐问题
- Linux编程:进程同步问题之哲学家就餐问题
- 进程(线程)间同步互斥经典问题(二)哲学家问题
- 操作系统学习笔记(13) 互斥与同步的经典问题 -哲学家进餐问题
- linux网络编程之System V 信号量(二):用信号量实现进程互斥示例和解决哲学家就餐问题
- 用信号量实现进程互斥示例和解决哲学家就餐问题
- 进程同步互斥——不死锁的哲学家问题
- linux网络编程之System V 信号量(二):用信号量实现进程互斥示例和解决哲学家就餐问题
- 操作系统清华大学版笔记(十) 信号量、管程、条件互斥、经典同步问题(读者写者、哲学家问题)
- 同步和互斥的问题
- [转]算法讨论:哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题 锁