Tag: producer

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(&...