#include CountingSemaphore::CountingSemaphore(int ini_value = 0) { count = ini_value; pthread_cond_init(&c, NULL); pthread_mutex_init(&c_m, NULL); pthread_mutex_init(&m, NULL); } CountingSemaphore::~CountingSemaphore( ) { pthread_cond_destroy(&c); pthread_mutex_destroy(&c_m); pthread_mutex_destroy(&m); } void CountingSemaphore::P(void) { while(1) { pthread_mutex_lock(&m); if(count > 0) { count--; pthread_mutex_unlock(&m); return; } pthread_mutex_unlock(&m); pthread_mutex_lock(&c_m); pthread_cond_wait(&c, &c_m); pthread_mutex_unlock(&c_m); } } void CountingSemaphore::V(void) { pthread_mutex_lock(&m); count ++; pthread_mutex_unlock(&m); pthread_cond_signal(&c); } void CountingSemaphore::SetVal(int num) { pthread_mutex_lock(&m); count = num; if(num > 0) pthread_cond_signal(&c); pthread_mutex_unlock(&m); }