3

所以我试图用一些信号量来解决哲学家的用餐问题..当我编译它时,我得到哲学家 1-5 正在思考,哲学家 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);

    }
 }
4

1 回答 1

0

我认为这是一个竞争条件。

state[RIGHT]在工作函数中指的是,但不能保证所有线程都已创建,以便state在该点初始化数组。

于 2013-01-06T16:10:01.297 回答