哲学家就餐问题,linux下实现。 - Go语言中文社区

哲学家就餐问题,linux下实现。


#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 W(){
          sem_wait(&sem);
      }
      void F(){
          sem_post(&sem);
      }
};
Semaphore mutex[N];
pthread_t thread[N];
pthread_mutex_t mutex1;
int id[N];
int add=0;
enum  state {think,hungry,eat};
state pid_state[N];
void *check_state(int a){
     int i =a;
    if(pid_state[i]==hungry&&pid_state[LEFT]!=eat&&pid_state[RIGHT]!=eat){
       pid_state[i]=eat;
       mutex[i].F();
    }
}
void *Do_take_fork(int param){
   int i =param;
   pthread_mutex_lock(&mutex1);
   pid_state[i]=hungry;
   check_state(i);
   pthread_mutex_unlock(&mutex1);
   mutex[i].W();
}
void *Do_put_fork(int param){
   int i=param;
   pthread_mutex_lock(&mutex1);
   pid_state[i]=think;
   check_state(LEFT);
   check_state(RIGHT);
   pthread_mutex_unlock(&mutex1);
}
void *solve(void*param){
    int i =*((int*)param);
    while(true){
       if(add>=30){
          cout<<"noodles is over"<<endl;
          break;
       }
       cout<<"philo"<<i<<"  is thinking"<<endl;
       sleep(1);
       cout<<"philo"<<i<<"  is hungry"<<endl;
       Do_take_fork(i);
       
       cout<<"philo"<<i<<"  is eatting"<<endl;
       add++;
       cout<<add<<endl;
       sleep(1);
       Do_put_fork(i);
    } 
}
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(){
    pthread_mutex_init(&mutex1,NULL);
    for(int i=0; i<N; i++){
        id[i]=i;
    }
    thread_create();
    thread_wait();
    return 0;
}

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/q275757160/article/details/80399790
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-02-25 02:32:30
  • 阅读 ( 972 )
  • 分类:Linux

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢