所以我试图用一些信号量来解决哲学家的用餐问题.. 当我编译它时,我得到哲学家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);
}
}
答案 0 :(得分:0)
我认为这是竞争条件。
你在worker函数中引用state[RIGHT]
,但不能保证所有线程都已创建,以便在那时初始化state
数组。