0

I have read through a whole bunch of producer-consumer problems that use semaphores, but I haven't been able to find an answer for this exact one. What I want to know is if this solution will ever deadlock?

semaphore loadedBuffer = 0
semaphore emptyBuffer = N where n>2
semaphore mutex = 1

Producer(){
    P(emptyBuffers)
    P(mutex)
    //load buffer
    V(loadedBuffers)
    v(mutex)

Consumer(){
    P(loadedBuffer)
    P(mutex)
    //empty buffer
    V(mutex)
    v(emptyBuffer)

I do believe this is a good solution, because I cannot find a circumstance where this would deadlock because any time the mutex semaphore is used, a thread cannot possibly be waiting on anything else.

Am I correct in assuming this is a good solution and will never deadlock?

Hopsain
  • 1
  • 2

1 Answers1

0

It's not quite clear what are those P(), V() and v() in your algorithm, but in general you need just two semaphores as described in Wikipedia:

semaphore fillCount = 0; // items produced
semaphore emptyCount = BUFFER_SIZE; // remaining space

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

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

Source: https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem#Using_semaphores

Andriy Berestovskyy
  • 8,059
  • 3
  • 17
  • 33