1
$\begingroup$

Wikipedia's solution for multi Producer-Consumer problem uses both mutexes and semaphores.

mutex buffer_mutex; 
semaphore fillCount = 0;
semaphore emptyCount = BUFFER_SIZE;

procedure producer() 
{
    while (true) 
    {
        item = produceItem();
        down(emptyCount);
        down(buffer_mutex);
        putItemIntoBuffer(item);
        up(buffer_mutex);
        up(fillCount);
    }
}

procedure consumer() 
{
    while (true) 
    {
        down(fillCount);
        down(buffer_mutex);
        item = removeItemFromBuffer();
        up(buffer_mutex);
        up(emptyCount);
        consumeItem(item);
    }
}

The reason given for using a mutex is to enforce mutual exclusion when multiple producers and consumers are in the critical section. My question is, since the goal is to have a single thread in the critical section anyway, why not just use a binary semaphore, which ensures this? That is, can we do away with the mutexes if we use binary semaphores in that example?

Can we have something like this instead?

semaphore empty = 1
semaphore full = 0
procedure producer() 
{
    while (true) 
    {
        down(empty);
        putItemIntoBuffer(item);
        up(full);
    }
}

procedure consumer() 
{
    while (true) 
    {
        down(full);
        item = removeItemFromBuffer();
        up(empty);
    }

}
$\endgroup$
  • $\begingroup$ Yes. Simply because a binary semaphore is a possible implementation of an advisory lock/mutex. The discussion preceding the code in the wikipedia could be improved. $\endgroup$ – Kai Nov 10 '18 at 6:02
  • $\begingroup$ Hi @Kai, Can you kindly elaborate? Can you, for e.g, describe a scenario in which not using a mutex could be a problematic, like in the edited version above? $\endgroup$ – abjoshi Nov 10 '18 at 15:23
  • $\begingroup$ Sorry, I interpreted your original question before the edit differently. The edited version doesn't make sense. It does not describe at all how a produced item is communicated to the consumer. $\endgroup$ – Kai Nov 10 '18 at 18:10
  • $\begingroup$ Hi, I edited it to clarify. We assume that there is shared queue between consumer and producer. When the producer gets into the c.s., it puts something into the buffer. When the consumer gets into the c.s., it gets an item. $\endgroup$ – abjoshi Nov 10 '18 at 19:14
  • $\begingroup$ This is wrong. You haven't described how the producer (consumer) reacts when the queue is full (empty). $\endgroup$ – Kai Nov 10 '18 at 20:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.