- 哲学家就餐问题(dining philosopher’s problem)是一个著名的并发问题,他由Dijkstra提出并解决。
- 这个问题的基本情况是:假定有5位“哲学家”围着一个圆桌。每两位哲学家之间有一把餐叉(一共5把)。哲学家有时要思考一会,不需要餐叉;有时又要就餐。而一位哲学家只有同时拿到左手边和右手边的两把餐叉,才能吃到东西。
- 解决方案(有问题):哲学家先拿左手边的餐叉,然后拿右边的餐叉,结束用餐时,将餐叉放下。
- 存在问题,当每个哲学家同时拿起左手边的餐叉时,此时所有的餐叉都被占有了,所有的哲学家都无法就餐,出现死锁问题。
- 代码表示死锁过程如下:
#include "stdio.h"
#include "pthread.h"
#include "semaphore.h"
#include "unistd.h"
sem_t forks[5];
int arg[5];
void* PhilosopherTh(void* arg)
{
int left,right;
switch (*(int*)arg)
{
case 0:
left = 0;
right = 4;
break;
case 1:
left = 1;
right = 0;
break;
case 2:
left = 2;
right = 1;
break;
case 3:
left = 3;
right = 2;
break;
case 4:
left = 4;
right = 3;
break;
}
while (1)
{
printf("哲学家%d在思考\n", *(int*)arg);
sem_wait(&forks[left]);
sem_wait(&forks[right]);
printf("哲学家%d在就餐\n", *(int*)arg);
sleep(0.5);
sem_post(&forks[left]);
sem_post(&forks[right]);
}
pthread_exit(0);
}
int main(void)
{
pthread_t philosopher_tid[5];
for (int i = 0; i < 5; i++)
{
sem_init(&forks[i], 0, 1);
}
for (int i = 0; i < 5; i++)
{
arg[i] = i;
pthread_create(philosopher_tid+i, NULL, PhilosopherTh, arg+i);
}
for (int i = 0; i < 5; i++)
{
pthread_join(philosopher_tid[i], NULL);
}
return 0;
}
该代码运行之后的结果为某一瞬间所有进程背阻塞:
- 使用破除依赖的方法解决死锁问题,主要思路:假定哲学家4的取餐顺序不同,代码实现如下所示:
#include "stdio.h"
#include "pthread.h"
#include "semaphore.h"
#include "unistd.h"
sem_t forks[5];
int arg[5];
void* PhilosopherTh(void* arg)
{
int left,right;
switch (*(int*)arg)
{
case 0:
left = 0;
right = 4;
break;
case 1:
left = 1;
right = 0;
break;
case 2:
left = 2;
right = 1;
break;
case 3:
left = 3;
right = 2;
break;
case 4:
left = 4;
right = 3;
break;
}
while (1)
{
printf("哲学家%d在思考\n", *(int*)arg);
if (*(int*)arg == 4)
{
sem_wait(&forks[right]);
sem_wait(&forks[left]);
}
else
{
sem_wait(&forks[left]);
sem_wait(&forks[right]);
}
printf("哲学家%d在就餐\n", *(int*)arg);
sleep(0.5);
sem_post(&forks[left]);
sem_post(&forks[right]);
}
pthread_exit(0);
}
int main(void)
{
pthread_t philosopher_tid[5];
for (int i = 0; i < 5; i++)
{
sem_init(&forks[i], 0, 1);
}
for (int i = 0; i < 5; i++)
{
arg[i] = i;
pthread_create(philosopher_tid+i, NULL, PhilosopherTh, arg+i);
}
for (int i = 0; i < 5; i++)
{
pthread_join(philosopher_tid[i], NULL);
}
return 0;
}
- 运行该代码后,进程不会出现阻塞的现象,成功解决死锁问题。