生产者-消费者问题、哲学家进餐问题(伪代码)

1.生产者-消费者问题

#define N 100
typedef int semaphore;
semaphore mutex=1;
semaphore full=0;
semaphore empty=N;//刚开始时无物品
void producer(void)
{
	int item;
	while(true){
	item=produce_item();
	P(empty);
	P(mutex);
	insert_item(item);
	V(mutex);
	V(full);
	}
}
void customer(void)
{
	int item;
	while(true){
	P(full);
	P(mutex);
	item=remove_item();
	V(mutex);
	V(empty);
	custome_item(item);
	}
}

2.哲学家进餐

#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;
semaphore s[N];
void philosopher(int i)
{
	while(true){
	think();
	take_forks(process);
	eat();
	put_forks(process);
	}
}
void take_forks(int i)
{
	P(mutex);
	state[i]=hungry;
	test(i);
	V(mutex);
	P(s[i]);
}
void put_forks(int i)
{
	P(mutex);
	state[i]=thinking;
	test(left);
	test(right);
	V(mutex);
}
void test(int i)
{
	if(state[i]==hungry && state[left]!=eating && state[right]!=eating)
	{
		state[i]=eating;
		V(S[i]);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值