Вопрос

Can anyone explain the producer-consumer problem to me when solved using semaphores? More specifically, I'm having trouble understanding what happens when the order of ups and downs is changed, both in the producer code and consumer.

semaphore mutex = 1;
semaphore full = 0;
semaphore empty = N;

void producer (void){
{
while(true)
{
int item = produce_item();
down(&empty);
down(&mutex);
insert_item(item);
up(&mutex);
up(&full);
}
}

void consumer (void){
{
while(true)
{
down(&full);
down(&mutex);
int item = remove_item(item);
up(&mutex);
up(&empty);
consume_item(item);
}
}

is the code i'm more or less talking about.

Это было полезно?

Решение

It looks like a semaphore implemented using busy waiting.

It works as follows:

The producer and the consumer are working parallel to each other. The mutex is for mutual exclusion. That means, that only one of them is accessing the incommon datastructure at the same time. down() is checking if the mutex is free (== 1 in this case). It is checking this in a while loop like: while (mutex < 1);. If the mutex is finally free, it decreases its value (called "taking the mutex").

The other two semaphores are for making sure two things:

  1. a consumer can only consume, if the datastructure is not empty
  2. a producer can only produce, if the datastructure is not full

This is necessary because one of both can be faster than the other one.

With down(&empty); the producer checks if there are empty slots in the datastructure. If this is not the case he is not allowed to produce yet (busy waiting until a slot is free, meaning empty > 0). Otherwise he decreases empty and continues. When he added his produced item in the datastructure he incereases the value of full slots with up(&full);.

With down(&full); the consumer checks if there are full slots to read. If this is not the case he is not allowed to read yet (busy waiting until a slot is full, meaning full > 0). Otherwise he decreases full and continues. When he consumed his item from the datastructure he increases the value of empty slots.

Changing the order of ups and downs could cause a deadlock, because they could be waiting for each other infinitely long.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top