//五个哲学家围坐在一起,两人之间都放有一个叉子,意大利面需要2个叉子吃,哲学家吃饭时候叉子只能拿左右手,哲学家除了吃饭时间其他时间都在思考
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <pthread.h>
#include <errno.h>
#include <math.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
//叉子作为mutex
pthread_mutex_t forkp[5] ;
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(;;){
sleep(rand()%4);//思考0~3秒
pthread_mutex_lock(&forkp[left]);//拿起左手的叉子
printf("哲学家 %c 拿起左手的叉子 %d\n", phi, left);
if (pthread_mutex_trylock(&forkp[right]) == EBUSY){//拿起右手的叉子
pthread_mutex_unlock(&forkp[left]);//如果右边叉子被拿走放下左手的叉子
printf("哲学家 %c 放下左手的叉子 %d\n", phi, left);
continue;
}
printf("哲学家 %c 拿起右手的叉子 %d\n", phi, right);
printf("哲学家 %c 在吃饭\n",phi);
printf("--------------------------------\n");
sleep(rand()%4);//吃0~3秒
pthread_mutex_unlock(&forkp[left]);
pthread_mutex_unlock(&forkp[right]);
}
}
int main(){
pthread_t A,B,C,D,E;
int i;
for (i = 0; i < 5; i++)
pthread_mutex_init(&forkp[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;
}