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!