/* * Semaphore-based implementation of bounded buffer. * * Also includes "atomic increment and test" for simulation. */ #include #include #include #include #include "test-bounded-buffer.h" #include "bounded-buffer.h" /* ---- global variables for synchronization ---- */ sem_t buffer_mutex; sem_t empty; sem_t full; sem_t counter_mutex; /* to allow simulation to end gracefully */ void init_synch(const int buffer_size) { sem_init(&buffer_mutex, 0, 1); sem_init(&empty, 0, buffer_size); sem_init(&full, 0, 0); sem_init(&counter_mutex, 0, 1); } void end_synch(void) { sem_destroy(&buffer_mutex); sem_destroy(&empty); sem_destroy(&full); sem_destroy(&counter_mutex); } void simulate_put_with_synch(const int producerID) { sem_wait(&empty); sem_wait(&buffer_mutex); simulate_put(producerID); sem_post(&buffer_mutex); sem_post(&full); } void simulate_get_with_synch(const int consumerID) { sem_wait(&full); sem_wait(&buffer_mutex); simulate_get(consumerID); sem_post(&buffer_mutex); sem_post(&empty); } bool atomic_increment(int * value, int const limit) { sem_wait(&counter_mutex); bool rval = (*value < limit); if (rval) { *value += 1; } sem_post(&counter_mutex); return rval; }