#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t lock[5];
void lock_init(){
int i;
for(i = 0;i<=4;i++){
pthread_mutex_init(&lock[i],0);
}
}
void lock_des(){
int i;
for(i = 0;i<=4;i++){
pthread_mutex_destroy(&lock[i]);
}
}
void *person(void* args){
int x= *(int*)args;
int left = x;
int right=(x+1)%5;
int i;
if(x==4){
for(i = 0;i<=9;i++){
printf("哲学家%d,开始思考\n",x);
sleep(2);
pthread_mutex_lock(&lock[right]);
printf("哲学家%d,拿起右边的%d号筷子\n",x,right);
pthread_mutex_lock(&lock[left]);
printf("哲学家%d,拿起左边的%d号筷子\n",x,x);
printf("哲学家%d,开始吃饭\n",x);
sleep(2);
printf("哲学家%d,吃完了\n",x);
pthread_mutex_unlock(&lock[left]);
printf("哲学家%d,放下左边的%d号筷子\n",x,x);
pthread_mutex_unlock(&lock[right]);
printf("哲学及%d,放下右手的%d号筷子\n",x,right);
sleep(2);
}}else{
for(i = 0;i<=9;i++){
printf("哲学家%d,开始思考\n",x);
sleep(2);
pthread_mutex_lock(&lock[left]);
printf("哲学家%d,拿起左边的%d号筷子\n",x,x);
pthread_mutex_lock(&lock[right]);
printf("哲学家%d,拿起右边的%d号筷子\n",x,right);
printf("哲学家%d,开始吃饭\n",x);
sleep(2);
printf("哲学家%d,吃完了\n",x);
pthread_mutex_unlock(&lock[left]);
printf("哲学家%d,放下左边的%d号筷子\n",x,x);
pthread_mutex_unlock(&lock[right]);
printf("哲学及%d,放下右手的%d号筷子\n",x,right);
sleep(2);
}
}
}
int main(){
lock_init();
pthread_t p0,p1,p2,p3,p4;
int i0 = 0,i1=1,i2=2,i3=3,i4=4;
pthread_create(&p0,0,person,&i0);
pthread_create(&p1,0,person,&i1);
pthread_create(&p2,0,person,&i2);
pthread_create(&p3,0,person,&i3);
pthread_create(&p4,0,person,&i4);
pthread_join(p0,0);
pthread_join(p1,0);
pthread_join(p2,0);
pthread_join(p3,0);
pthread_join(p4,0);
lock_des();
}