经典IPC问题

1.哲学家进餐

#define N   5
#define LEFT (i+N-1)%5
#define RIGHT (i+1)%5
#define THINKING 0
#define HUNGRY 1
#define EATING 2
typedef int semaphore;
int state[N];
semaphore mutex=1;
semaphore s[N];

void philosopher(int i){
	while(TRUE){
		think();
		take_forks(i);
		eat();
		put_forks(i);
	}
}
void take_forks(i){
	down(&mutex);
	state[i]=HUNGRY;
	test(i);
	up(&mutex);
	down(&s[i]);
}

void put_forks(i){
	down(&mutex);
	state[i]=THINKING;
	test(LEFT);
	test(RIGHT);
	uo($mutex);
}
void test(i){
	if(state[i]==HUNGRY&&state[LEFT]!=EATING&&state[RIGHT]!=EATING){
	state[i]=EATING;
	up(&s[i]);
	}
}
发布了11 篇原创文章 · 获赞 1 · 访问量 45

猜你喜欢

转载自blog.csdn.net/weixin_44384461/article/details/105435262
IPC