今天刚看的,整了半天,也不知道对不对,放上来给大家看下。。。,我在别处看到的哲学家吃饭还有thinking的状态,我没觉得有啥用, 因此就两个状态HUNGRY和EATING
#include"../myinc.h"
#define N 5//哲学家数目
#define HUNGRY 1
#define EATING 2
pthread_mutex_t pm[N];
int state[N];
pthread_mutex_t mutex;
pthread_mutex_t eatmutex;
void* philosopherEate(void* arg){
int th_xh=*(int*)arg;
int left_xh, right_xh;
if(th_xh==0){
left_xh=N-1;
}else{
left_xh=th_xh-1;
}
right_xh=th_xh;
while(1){
//检查是否能吃饭,如果可以那么把叉子拿起来
pthread_mutex_lock(&mutex);
if(state[left_xh]==HUNGRY && state[right_xh]==HUNGRY){
pthread_mutex_lock(pm+left_xh);
pthread_mutex_lock(pm+right_xh);
state[th_xh]=EATING;
printf("%d begin eating\n", th_xh);
}
pthread_mutex_unlock(&mutex);
usleep(10); //为了测试不妨碍其他进程吃饭.
//如果在吃饭,那么吃完后把叉子释放
if(state[th_xh]==EATING){
pthread_mutex_lock(&eatmutex);
sleep(1);
printf("%d end eating\n", th_xh);
state[th_xh]=HUNGRY;
pthread_mutex_unlock(pm+left_xh);
pthread_mutex_unlock(pm+right_xh);
pthread_mutex_unlock(&eatmutex);
}
}
}
int main(){
pthread_t th[N];
int bh[N]={0,1,2,3,4};
int bh0=0,bh1=1,bh2=2,bh3=3,bh4=4;
int retcode;
int i=0;
for(;i<N;i++){
state[i]=HUNGRY;
retcode=pthread_create(th+i, NULL, philosopherEate, (void*)(bh+i));
if(retcode!=0){
err_exit("%d: th create error");
}
}
for(i=0;i<N;i++){
retcode=pthread_join(th[i], NULL);
if(retcode!=0){
err_exit("th join error");
}
}
return 0;
}
结果:
1 begin eating
3 begin eating
3 end eating
1 end eating
0 begin eating
0 end eating
4 begin eating
2 begin eating
4 end eating
2 end eating
..........................