3
所以我試圖解決哲學家就餐問題與一些信號燈..當我編譯它我得到哲學家1-5思考,phisopher 1是餓他叉叉 5和1,哲學家3餓了,然後該程序停在那裏......我不知道這個問題。哲學家用餐
#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
#define N 5
#define THINKING 0
#define HUNGRY 1
#define EATING 2
#define LEFT (i+4)%N
#define RIGHT (i+1)%N
sem_t mutex;
sem_t S[N];
void * philospher(void *num);
void take_fork(int);
void put_fork(int);
void test(int);
int state[N];
int phil_num[N]={0,1,2,3,4};
int main()
{
int i;
pthread_t thread_id[N];
sem_init(&mutex,0,1);
for(i=0;i<N;i++)
sem_init(&S[i],0,1);
for(i=0;i<N;i++)
{
pthread_create(&thread_id[i],NULL,philospher,(void *)i);
printf("Philosopher %d is thinking\n",i+1);
}
for(i=0;i<N;i++)
pthread_join(thread_id[i],NULL);
}
void *philospher(void *num)
{
while(1)
{
int i;
i = (int)num;
sleep(1);
//take_fork(i);
sem_wait(&mutex);
state[i] = HUNGRY;
printf("Philosopher %d is Hungry\n",i+1);
//test(i);
if (state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING)
{
sem_wait(&S[LEFT]);
sem_wait(&S[RIGHT]);
state[i] = EATING;
sleep(2);
printf("Philosopher %d takes fork %d and %d\n",i+1,LEFT+1,i+1);
printf("Philosopher %d is Eating\n",i+1);
}
sem_post(&mutex);
sleep(1);
//put_fork(*i);
sem_wait(&mutex);
state[i] = THINKING;
printf("Philosopher %d putting fork %d and %d down\n",i+1,LEFT+1,i+1);
printf("Philosopher %d is thinking\n",i+1);
sem_post(&S[LEFT]);
sem_post(&S[RIGHT]);
//test(LEFT);
//test(RIGHT);
sem_post(&mutex);
}
}
歡迎來到Stack Overflow!要求人們發現代碼中的錯誤並不是富有成效的。您應該使用調試器(或添加打印語句)來隔離問題,然後構造一個[最小測試用例](http://sscce.org)。 –
當我編譯它theres沒有錯。但是當我運行它打印一些結果,但程序暫停?(不知道這是否是正確的詞)爲某種原因。 – user1953024