linux 哲学家进餐问题 奇数偶数号科学家
来源:互联网 发布:sql update 多个行 编辑:程序博客网 时间:2024/06/05 08:53
规定奇数号哲学家先去拿他左边的筷子,然后再去拿右边的筷子;偶数号哲学家则相反。按此规定,将是1,2号哲学家竞争1号筷子;3,4号哲学家竞争3号筷子。即五位哲学家都先竞争奇数号筷子,获得后,再去竞争偶数号筷子,最后总有一位哲学家能够获得两只筷子而进餐。#include<iostream>#include<stdio.h>#include<stdlib.h>#include<pthread.h>#include<unistd.h>#include<semaphore.h>#define N 5#define LEFT i#define RIGHT (i+1)%Nusing namespace std;sem_t mutex[N];int id[N]={0,1,2,3,4};pthread_t thread[N];void* solve(void*param){ int i=*((int*)param); while(true){ if(i%2==0){ sem_wait(&mutex[LEFT]); sem_wait(&mutex[RIGHT]); cout<<"phlio"<<i<<" is eatting"<<endl; sleep(1); sem_post(&mutex[RIGHT]); sem_post(&mutex[LEFT]); cout<<"phlio"<<i<<" is over"<<endl; sleep(1); }else{ sem_wait(&mutex[RIGHT]); sem_wait(&mutex[LEFT]); cout<<"phlio"<<i<<" is eatting"<<endl; sleep(1); sem_post(&mutex[LEFT]); sem_post(&mutex[RIGHT]); cout<<"phlio"<<i<<" is over"<<endl; sleep(1); } }}int main(){ for(int i=0; i<N; i++){ sem_init(&mutex[i],0,1); pthread_create(&thread[i],NULL,solve,&id[i]); } for(int i=0; i<N; i++){ pthread_join(thread[i],NULL); } return 0;}
阅读全文
0 0
- linux 哲学家进餐问题 奇数偶数号科学家
- linux 哲学家进餐问题
- linux 哲学家进餐问题 c++
- 哲学家进餐问题
- 哲学家进餐的问题
- 哲学家进餐问题
- 哲学家进餐问题
- 关于哲学家进餐问题
- 哲学家进餐问题
- 哲学家进餐问题
- 哲学家进餐问题
- 关于哲学家进餐问题
- 哲学家进餐问题:
- 哲学家进餐问题
- 哲学家进餐问题
- 哲学家进餐问题
- 哲学家进餐问题
- 哲学家进餐问题
- phpstorm激活
- os.getcwd && os.path.abspath详解
- div怎么添加一个点击事件onClick?
- 修改Tomcat服务器Server Locations
- 下拉菜单(css、jq)
- linux 哲学家进餐问题 奇数偶数号科学家
- Day15—List集合、Queue集合、Set集合
- 学习记录
- 向邮箱发送验证码去验证邮箱或者密码等等
- 平衡二叉树 之 AVL树
- CSS+ DIV布局
- 数据挖掘模型效果评估方法汇总
- Mycat系列—Mysql读写分离+强制走写节点+根据主从延时的读写分离
- 常见水平垂直居中问题