哲学家就餐问题

今天刚看的,整了半天,也不知道对不对,放上来给大家看下。。。,我在别处看到的哲学家吃饭还有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
..........................

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值