我们有一项任务,以显示与餐饮哲学家问题的僵局。我们编写了所有代码并编译代码,但在运行代码时,其中一位哲学家最终会吃掉。那么这是不是意味着死锁实际上并未发生?
#include <pthread.h>
#include <stdio.h>
#define number_philo 5
pthread_mutex_t cutlery[number_philo];
void* philosopher (void* number)
{
int my_num = *((int*)number);
while (1)
{
printf("\n Philosopher %d is thinking.\n",my_num);
pthread_mutex_lock (&cutlery[my_num]);
printf("\nPhilosopher %d has left cutlery. \n",my_num);
sleep(3);
pthread_mutex_lock (&cutlery[(my_num + 1) % number_philo]);
printf("\nPhilosopher %d has right cutlery. \n",my_num);
printf("\n Philosopher %d eating.\n", my_num);
printf("\n Philosopher %d done.\n", my_num);
pthread_mutex_unlock (&cutlery[(my_num + 1) % number_philo]);
pthread_mutex_unlock (&cutlery[my_num]);
printf("\nPhilosopher %d no longer has cutlery.\n", my_num);
}
return NULL;
}
int main ()
{
int i;
pthread_t phils[number_philo];
void* return_val;
for (i = 0; i < number_philo; i++)
pthread_mutex_init (&cutlery[i], NULL);
for (i = 0; i < number_philo; i++)
pthread_create (&phils[i], NULL, philosopher, &i);
for (i = 0; i < number_philo; i++)
pthread_join (phils[i], &return_val);
return 0;
}
这是输出:output
答案 0 :(得分:0)
问题在于:
pthread_create (&phils[i], NULL, philosopher, &i);
您正在向每个线程传递指向同一变量i
的指针,并且这些线程(和主线程)都以一种活泼的方式访问i
。你会得到多个哲学家使用相同的数字和一些根本没用过的数字。
你需要给每个哲学家自己的变量来阅读,或者在循环并改变i
之前等待它阅读i
。前者的一个例子:
int phil_num[number_philo];
/* ... */
for (i = 0; i < number_philo; i++)
{
phil_num[i] = i;
pthread_create (&phils[i], NULL, philosopher, &phil_num[i]);
}