一、生产者-消费者问题
semaphore mutex=1;
semaphore empty=n;
semaphore full=0;
producer()
{
while(1)
{
produce an item in nextp;
P(empty);
P(mutex);
add nextp in buffer;
V(full);
V(mutex);
}
}
consumer()
{
while(1)
{
P(full);
P(mutex);
remove an item form buffer;
V(empty);
V(mutex);
consum an item;
}
}
对生产者消费者问题指向P操作的时候,如果执行顺序是mutex,empty,mutex,full,那么会导致什么问题呢,生产者先封锁mutex,然后empty为n,那么消费者封锁mutex,但是此时mutex被生产者封锁,这样导致了生产者和消费者都处在等待被唤醒的状态,造成死锁。所以P操作,一定是按照empty,mutex,full,mutex的顺序执行,释放V操作无论先后顺序。
二、多生产者-多消费者问题
桌子上有一只盘子,每次只能向其中放入一个水果。爸爸专向盘子中放苹果,妈妈专向盘子中放橘子,儿子专等吃盘子中的橘子,女儿专等吃盘子中的苹果。只有盘子为空时,爸爸或妈妈就可向盘子中放一个水果;仅当盘子中有自己需要的水果时,儿子或女儿可以从盘子中取出。
思路:dad() daughter() mom() son() 按照这样的顺序执行
semaphore plate=1,apple=0,orange=0;
dad()//apple