1、问题分析
五根筷子是资源,当哲学家拿到两支筷子,即左右手旁的筷子,哲学家才能吃饭。
当哲学家都拿到左手或右手的筷子后,资源都被占用,没有一个哲学家能拿到两个筷子进餐。哲学家都等待对方释放资源,这就造成了死锁。
死锁产生的条件有
(1) 互斥即资源不能共享,只能由一个进程占用
(2)占有且等待即当一个等待另外进程而阻塞时,资源不主动释放
(3)不可抢占即操作系统不能强行抢占被进程持有的资源
(3)循环等待即存在一个封闭的进程链,使得每一个进程都至少占有下个进程所需要的资源。
这个四个资源中,前面三个,基本所有操作系统都是可以满足的。所以一般产生死锁,第四个是关键。
2、对于进餐问题如何避免死锁呢?
当一个哲学家拿到左边筷子时,去申请右边筷子。如果能申请到,哲学家则可以进餐;如果不能申请到,哲学家需要把已经拿到的左边的筷子放下,当旁边人申请这根筷子时,就可以申请到,这样就可以避免死锁。
3、避免死锁代码如下
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <pthread.h>
#include <errno.h>
#include <math.h>
//筷子作为mutex
pthread_mutex_t chopstick[6] ;
void *eat_think(void *arg)
{
char phi = *(char *)arg;
int left,right; //左右筷子的编号
switch (phi){
case 'A':
left = 5;
right = 1;
break;
case 'B':
left = 1;
right = 2;
break;
case 'C':
left = 2;
right = 3;
break;
case 'D':
left = 3;
right = 4;
break;
case 'E':
left = 4;
right = 5;
break;
}
int i;
for(;;){
usleep(800000); //思考
pthread_mutex_lock(&chopstick[left]); //拿起左手的筷子
printf("Philosopher %c fetches chopstick %d\n", phi, left);
if (pthread_mutex_trylock(&chopstick[right]) == EBUSY){ //拿起右手的筷子
pthread_mutex_unlock(&chopstick[left]); //如果右边筷子被拿走放下左手的筷子
printf("Philosopher %c release chopstick %d\n", phi, left);
continue;
}
// pthread_mutex_lock(&chopstick[right]); //拿起右手的筷子,如果想观察死锁,/把上一句if的所有语句注释掉,再把这一句加上
printf("Philosopher %c fetches chopstick %d\n", phi, right);
printf("Philosopher %c is eating.\n",phi);
usleep(300000); //吃饭
pthread_mutex_unlock(&chopstick[left]); //放下左手的筷子
printf("Philosopher %c release chopstick %d\n", phi, left);
pthread_mutex_unlock(&chopstick[right]); //放下右手的筷子
printf("Philosopher %c release chopstick %d\n", phi, right);
}
}
int main(){
pthread_t A,B,C,D,E; //5个哲学家
int i;
for (i = 0; i < 5; i++)
{
pthread_mutex_init(&chopstick[i],NULL);
}
pthread_create(&A,NULL, eat_think, "A");
pthread_create(&B,NULL, eat_think, "B");
pthread_create(&C,NULL, eat_think, "C");
pthread_create(&D,NULL, eat_think, "D");
pthread_create(&E,NULL, eat_think, "E");
pthread_join(A,NULL);
pthread_join(B,NULL);
pthread_join(C,NULL);
pthread_join(D,NULL);
pthread_join(E,NULL);
return 0;
}
4、如果想要观察死锁的话可以把申请右手筷子的if语句注释掉,再在原来If语句的位置加上pthread_mutex_lock(&chopstick[right]); //直接申请右手筷子的资源,不管是否能申请到
//注释掉这一部分,观察死锁
if (pthread_mutex_trylock(&chopstick[right]) == EBUSY){ //拿起右手的筷子
pthread_mutex_unlock(&chopstick[left]); //如果右边筷子被拿走放下左手的筷子
printf("Philosopher %c release chopstick %d\n", phi, left);
continue;
}
//这里加上下面这一条代码
pthread_mutex_lock(&chopstick[right]); //拿起右手的筷子,如果想观察死锁,/把上一句if的所有语句注释掉,再把这一句加上
5、编译时使用 gcc -o lianxi lian.c -lpthread,这里lianxi是我要生成的可执行文件,lian.c是我要编译的.c文件。后面一定不要忘记加-lpthread。
6、运行效果