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

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]);
	}
}

版权声明:本文为qq_42717239原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。