餐饮哲学家计划C.

我正在与5位哲学家和5根筷子一起处理经典的餐饮哲学家问题。 我的作业是使用1个互斥量和5个条件。 我得到了它的工作,但我不知道为什么哲学家1从不吃,但4,3,0吃,2吃两次。 这是我的代码(抱歉长度):

//To compile: gcc -pthread -o monitor monitor.c //To execute: ./monitor "an integer as the amount of food (default = 5)" #include  #include  #include  // There are 5 philosophers (0,1,2,3,4) and 5 chopsticks (0,1,2,3,4) #define NUM 5 // States of a philosopher #define THINKING 0 #define HUNGRY 1 #define EATING 2 int food = 5; //The total amount of food on the table. int monitor = HUNGRY; int state[NUM]; //The state of a particular philosopher during the simulation //The mutex for monitor variable and the condition resource_ready pthread_mutex_t monitor_mutex; pthread_cond_t resource_ready; //The philosopher thread identifiers pthread_t philo[NUM]; void *philosopher (void *num); void get_chopsticks (int, int, int); void test (int); void put_chopsticks (int, int, int); int main (int argc, char **argv) { if (argc == 2) food = atoi (argv[1]); int i; pthread_mutex_init (&monitor_mutex, NULL); pthread_cond_init (&resource_ready, NULL); //Create a thread for each philosopher for (i = 0; i < NUM; i++) pthread_create (&philo[i], NULL, philosopher, (void *)i); //Wait for the threads to exit for (i = 0; i  0) { //Get the chopstick get_chopsticks (id, left_chopstick, right_chopstick); sleep(1); } return (NULL); } void get_chopsticks (int phil, int c1, int c2) { //Lock monitor variable pthread_mutex_lock (&monitor_mutex); state[phil] = monitor;//state[phil] = HUNGRY test(phil); if (state[phil] != EATING) { pthread_cond_wait (&resource_ready, &monitor_mutex); printf ("Philosopher %d is now eating\n", phil); food--; //1 food is eaten if (food == 0) { printf ("There is no more food on the table. Program exit\n"); pthread_mutex_destroy(&monitor_mutex); pthread_cond_destroy(&resource_ready); exit(1); } printf ("There are/is %d food(s) left\n", food); put_chopsticks (phil, c1, c2); sleep(1); } //Unlock monitor variable pthread_mutex_unlock (&monitor_mutex); } void test (int phil) { //If the philosopher is hungry and the nearest 2 are not eating, he then eats. if ((state[(phil+4)%NUM] != EATING)&& (state[phil] == HUNGRY)) { state[phil] = EATING; pthread_cond_signal (&resource_ready); } } void put_chopsticks (int phil, int c1, int c2) { state[phil] = THINKING; //Check the 2 nearest philosophers to see if they are eating test ((phil+4)%NUM); test ((phil+1)%NUM); } 

您应该#define NUM 5而不是#define NUM 7 。 这导致你在put_chopsticks()test()模运算是错误的,可能是其他奇怪的事情。

你似乎在你传递给哲学家线程的int中有一个竞争条件,因为它们都指向i的相同索引地址(并且你应该在这里得到关于错误类型的编译器警告)。

我已经停止了,因为你在这里遇到太多问题,那些只是为了开始。

右筷子的位置与哲学家的位置相同。 所以根据你的代码,第一位哲学家永远不会拥有第五位哲学家的筷子(这与他们坐在圆桌上的想法相矛盾)。

因此,只需在函数中尝试此操作即可

 right_chopstick = (id+1)%NUM ; left_chopstick = (id+(NUM-1))%NUM; 

我希望这会让你的第一位哲学家吃饭

并且让所有哲学家都吃,当他们将状态从思考改为吃,并试图改变他们的状态时,尝试引入睡眠时间。