0

I'm solving a producer-consumer problem with additional conditions using semaphores. For example: consumer cannot read from the buffer until there are at least 3 elements in it. My question is: are conditions like these easily expressible using only down() and up() operation on additional semaphores? To specify: the semaphores I'm using are the ones from POSIX < semaphore.h >. They do not support negative semaphore values.

So far I came up with this:

void* consumer(void* param) 
{
    while(true) {
        sem_wait(&full);
        sem_wait(&mutex);

        if( buffer.size() < 3 ) {
            // cancel an attempt to take an item from a buffer
            sem_post(&full);
        } else {
            consume_item();
            sem_post(&empty);
        }

        sem_post(&mutex);
    }
}

It works but the consumer is given time which he spends only on finding out that he can do nothing. Can we avoid that?

Thank you for your help!

borrisso
  • 61
  • 1
  • 4
  • 1
    The producer should post a notification only when the size of the queue is at least 3. – Shloim Nov 30 '15 at 21:37
  • ^^what @Shloim says. The producer counts up to 3 and then either posts three units to the semaphore, or one unit and the consumer understands that means three items are waiting for it. – Martin James Dec 01 '15 at 12:18

0 Answers0