#ifndef SEMAPHORE_HH #define SEMAPHORE_HH #include struct Semaphore { int value; pthread_mutex_t mutex; }; void init (Semaphore& s, int value) { s.value = value; // initialize mutex pthread_mutex_init(&(s.mutex), NULL); } void P (Semaphore& s) { pthread_mutex_lock(&(s.mutex)); while (s.value == 0) { // active wait pthread_mutex_unlock(&(s.mutex)); pthread_mutex_lock(&(s.mutex)); } s.value = s.value - 1; pthread_mutex_unlock(&(s.mutex)); } void V (Semaphore& s) { pthread_mutex_lock(&(s.mutex)); s.value = s.value + 1; pthread_mutex_unlock(&(s.mutex)); } void destroy (Semaphore& s) { // cleanup mutex pthread_mutex_destroy(&(s.mutex)); } #endif // SEMAPHORE_HH