#include<stdio.h>#include<pthread.h>#include<unistd.h>#include<semaphore.h>#defineN5sem_t chops[N];void*dine(void*args){int i =(int)args;//哲学家编号0-4while(1){//哲学家思考//对于偶数编号的哲学家,先拿左边筷子,后拿右边筷子if(i %2==0){sem_wait(&chops[i]);sem_wait(&chops[(i +1)% N]);}//对于奇数编号的哲学家,先拿右边筷子,后拿左边筷子else{sem_wait(&chops[(i +1)% N]);sem_wait(&chops[i]);}//哲学家用餐中printf("%d 号哲学家用餐中...\n",i);//用餐完毕后放下筷子sem_post(&chops[i]);sem_post(&chops[(i +1)% N]);sleep(1);}}intmain(){pthread_t philosopher[N];for(int i =0; i < N; i++){pthread_create(&philosopher[i],NULL,dine,(void*)i);sem_init(&chops[i],0,1);}for(int i =0; i < N; i++){pthread_join(philosopher[i],NULL);}for(int i =0; i < N; i++){sem_destroy(&chops[i]);}}
只允许最多4个哲学家入场,避免死锁
#include<stdio.h>#include<pthread.h>#include<unistd.h>#include<semaphore.h>#defineN5//哲学家个数#defineLEFTi // i 的左边叉子#defineRIGHT(i +1)% N // i 的右边叉子sem_t chop[N];//每个筷子信号量为1sem_t room;//只允许最多4个哲学家入场,打破死锁//功能:要么拿到两把叉子,要么被阻塞起来voidtake_chops(int i){sem_wait(&chop[LEFT]);sem_wait(&chop[RIGHT]);}//用餐完毕,通知左邻右舍voidput_chops(int i){sem_post(&chop[LEFT]);sem_post(&chop[RIGHT]);}//哲学家主代码voidprocess(void*args){int i =(int)args;while(1){sem_wait(&room);//think();take_chops(i);printf("%d 号哲学家用餐中\n",i);//eat()put_chops(i);sem_post(&room);sleep(1);}}intmain(){pthread_t philosopher[N];sem_init(&room,0,4);for(int i =0; i < N; i++){pthread_create(&philosopher[i],NULL,process,(void*)i);sem_init(&chop[i],0,1);}for(int i =0; i < N; i++){pthread_join(philosopher[i],NULL);}sem_destroy(&room);for(int i =0; i < N; i++){sem_destroy(&chop[i]);}}