Jovan Perovic
Jovan Perovic

Reputation: 20193

POSIX semaphore upper limit

I am looking into utilizing semaphores as classic counter. It would have a starting value of 5, which could go down to 0, but could not go above 5.

sem_t sem;
sem_init(&sem, 0, 5);

// ...

sem_wait(&sem); // goes down to 4

//...

sem_post(&sem); // goes up to 5
sem_post(&sem); // goes up to 6 ?! 

I went thought the docs, but I don't see any sem_post-like function which does just that. Now, I know this behavior could implemented with mutex and int, but I was kind of interested if similar thing could be done this way (a bit less of code).

Upvotes: 0

Views: 2262

Answers (1)

doron
doron

Reputation: 28892

Semaphores block the waiter/decrementer (consumer) not the poster/incrementer. This means that there is no mechanism to prevent the increments to above 5 from happening. Therefore if you want to block both waiter/consumer and poster/incrementer (to prevent going above 5) you will need to use a combination of mutex and conditional variable. There is no other way.

Upvotes: 1

Related Questions