How to do a counting semaphore with pthread library in c++

I was struggling to find a good source of information for counting semaphore using the pthread library, so I figured I would summarize my findings here.

If you have a buffer of N length you need to use and empty and full semaphore to ensure that the consumer does not consume an empty buffer and the producer does not produce into a full buffer. So!

// Allocate globally
sem_t sem_empty;
sem_t sem_full;

// Initialize to values
sem_init(&sem_full, 0, 0);
sem_init(&sem_empty, 0, BUFFER_SIZE);


Once initialized, the threads will wait if the semaphore value is equal to 0.

// For the producer
sem_wait(&sem_empty); // Decrements the sem_empty value by 1
insert_item(temp);
sem_post(&sem_full); // Increments the sem_full by 1

// For the consumer
sem_wait(&sem_full); // Decrements the sem_full value by 1
insert_item(temp);
sem_post(&sem_empty); // Increments the sem_empty by 1

Leave a Reply

Your email address will not be published. Required fields are marked *