哲学家就餐问题
来源:互联网 发布:网络专升本 编辑:程序博客网 时间:2024/04/30 18:42
五个哲学家围坐在一张圆桌周围,每个哲学家面前都有一盘通心粉。由于通心粉很滑,所以需要两把叉子才能夹住。相邻两个盘子之间放有一把叉子。能为每一个哲学家写一段描述其行为的程序,且绝不会死锁吗?
#include <pthread.h>#include <stdio.h>#define N 5#define LEFT (i+N-1)%N#define RIGHT (i+1)%N#define THINK_TIME 3#define EAT_TIME 2enum { THINKING, HUNGRY, EATING } state[N];pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER, s[N];void test(int i){ if (state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING) { state[i] = EATING; pthread_mutex_unlock(&s[i]); }}void take_forks(int i){ pthread_mutex_lock(&mutex); state[i] = HUNGRY; test(i); //尝试获取2把叉子 pthread_mutex_unlock(&mutex); pthread_mutex_lock(&s[i]); //得不到需要就阻塞}void put_forks(int i){ pthread_mutex_lock(&mutex); state[i] = THINKING; test(LEFT); //检查左边的邻居现在可不可以吃 test(RIGHT); //检查右边的邻居现在可不可以吃 pthread_mutex_unlock(&mutex);}void think(int i){ printf("philosopher %d is thinking...\n", i); sleep(THINK_TIME);}void eat(int i){ printf("philosopher %d is eating...\n", i); sleep(EAT_TIME);}void* phi(void* vargp){ int i = *(int*)vargp; while (1) { think(i); take_forks(i); eat(i); put_forks(i); } return NULL;}int main(){ int i; pthread_t tid[N]; for (i = 0; i < N; i++) pthread_create(&tid[i], NULL, phi, (void*)(&i)); for (i = 0; i < N; i++) pthread_join(tid[i], NULL); return 0;}
0 0
- 哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题 锁
- 哲学家就餐问题
- 哲学家就餐问题
- 关于哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题
- 多线程--哲学家就餐问题
- LeetCode 326:Power of Three
- java字符串按照逗号分开
- Mysql中DATETIME、DATE和TIMESTAMP类型的特征和区别
- 流数据平台阅读笔记
- Retrofit+RxJava实战日志(3)-网络异常处理
- 哲学家就餐问题
- HDU【1180】诡异的楼梯
- python简单爬虫--转源码
- Windows 平台下 LiteIDE 的安装和使用
- Spring MVC_HandlerInterceptorAdapter的使用
- java操作Excel的工具—POI学习
- Spring学习笔记1——Spring JDBC
- ActiveMQ的入门实例demo
- Java中UIManager类的几种外观风格