linux 哲学家进餐问题 c++
来源:互联网 发布:mac模糊搜索文件 编辑:程序博客网 时间:2024/06/05 16:13
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<iostream>
#include<unistd.h>
#include<semaphore.h>
#define N 5
#define LEFT i
#define RIGHT (i+1)%N
using namespace std;
class Semaphore{
private:
sem_t sem;
public:
Semaphore(int value=1){
sem_init(&sem,0,value);
}
void P(){
sem_wait(&sem);
}
void V(){
sem_post(&sem);
}
};
Semaphore mutex[N];
pthread_t thread[N];
int id[N];
int add=0;
void* solve(void*param){
int i =*((int*)param);
while(true){
if(add>=30){
cout<<"noodles is over"<<endl;
break;
}
cout<<"philo"<<i<<" thinking"<<endl;
if(i%2==0){
mutex[LEFT].P();
mutex[RIGHT].P();
cout<<"philo"<<i<<" eatting"<<endl;
add++;
cout<<add<<endl;
mutex[RIGHT].V();
mutex[LEFT].V();
}else{
mutex[RIGHT].P();
mutex[LEFT].P();
cout<<"philo"<<i<<" eatting"<<endl;
add++;
cout<<add<<endl;
mutex[LEFT].V();
mutex[RIGHT].V();
}
sleep(1);
}
}
void thread_create(){
int tmp;
for(int i=0; i<N; i++){
tmp=pthread_create(&thread[i],NULL,solve,&id[i]);
if(tmp!=0){
cout<<"thread"<<i<<"error"<<endl;
}
}
}
void thread_wait(){
for(int i=0; i<N; i++){
pthread_join(thread[i],NULL);
}
}
int main(){
for(int i=0; i<N; i++){
id[i]=i;
}
thread_create();
thread_wait();
return 0;
}
阅读全文
0 0
- linux 哲学家进餐问题
- C-多线程-哲学家进餐问题
- linux 哲学家进餐问题 c++
- 哲学家进餐问题的C语言实现
- 哲学家进餐问题的c语言代码
- 哲学家进餐问题C语言实现
- 哲学家进餐问题
- 哲学家进餐的问题
- 哲学家进餐问题
- 哲学家进餐问题
- 关于哲学家进餐问题
- 哲学家进餐问题
- 哲学家进餐问题
- 哲学家进餐问题
- 关于哲学家进餐问题
- 哲学家进餐问题:
- 哲学家进餐问题
- 哲学家进餐问题
- erlang高性能网络库esockd的编译和使用(五)-热更新
- QT之qss教程-QToolBox
- Android Camera详解
- android studo 3.0 搜狗输入法问题 终结者
- Android studio 解决各种错误
- linux 哲学家进餐问题 c++
- 优化代码建议
- HBase之HRegionServer处理put请求
- 技术分享连载(四十八)
- Opencv cvCircle()函数
- 服务器常见错误代码500、501、502、503、504、505
- 《高性能iOS 应用开发》之降低你 APP 的电量消耗
- tomcat源码解读一 Digester的解析方式
- window.onload()函数解析