我正致力于餐饮哲学家计划。然而,我遇到了一个问题,我的程序在所有哲学家都吃过之前停止了,我不明白为什么。这是我现在的代码:
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void *func(int n);
pthread_t philosopher[5];
pthread_mutex_t chopstick[5];
int main()
{
int i;
void *msg;
for(i=1;i<=5;i++)
{
pthread_mutex_init(&chopstick[i],NULL);
}
for(i=1;i<=5;i++)
{
pthread_create(&philosopher[i],NULL,(void *)func,(int *)i);
}
for(i=1;i<=5;i++)
{
pthread_join(philosopher[i],&msg);
}
for(i=1;i<=5;i++)
{
pthread_mutex_destroy(&chopstick[i]);
}
return 0;
}
void *func(int n)
{
printf ("\nPhilosopher %d is thinking ",n);
pthread_mutex_lock(&chopstick[n]);//when philosopher 5 is eating he takes fork 1 and fork 5
pthread_mutex_lock(&chopstick[(n+1)%5]);
printf ("\nPhilosopher %d is eating ",n);
sleep(3);
pthread_mutex_unlock(&chopstick[n]);
pthread_mutex_unlock(&chopstick[(n+1)%5]);
printf ("\nPhilosopher %d finished eating ",n);
}
答案 0 :(得分:5)
我在SLES 11服务器上多次运行问题代码。我没有观察到问题中指出的问题。
然而,您需要更改以下的for()语句:
for(i=1;i<=5;i++)
到
for(i=0;i<5;i++)
在任何情况下,问题代码中都可能会发生一些变化。 (答案没什么关键):
以下是我最终得到的代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_t philosopher[5];
pthread_mutex_t chopstick[5];
void *func(int n)
{
printf ("Philosopher %d is thinking\n",n);
//when philosopher 5 is eating he takes fork 1 and fork 5
pthread_mutex_lock(&chopstick[n]);
pthread_mutex_lock(&chopstick[(n+1)%5]);
printf ("Philosopher %d is eating\n",n);
sleep(3);
pthread_mutex_unlock(&chopstick[n]);
pthread_mutex_unlock(&chopstick[(n+1)%5]);
printf ("Philosopher %d finished eating\n",n);
return(NULL);
}
int main()
{
int i;
for(i=0;i<5;i++)
pthread_mutex_init(&chopstick[i],NULL);
for(i=0;i<5;i++)
pthread_create(&philosopher[i],NULL,(void *)func,(void *)i);
for(i=0;i<5;i++)
pthread_join(philosopher[i],NULL);
for(i=0;i<5;i++)
pthread_mutex_destroy(&chopstick[i]);
return 0;
}