#include /* for NULL */ #include "semaphore.h" semaphore_p newSemaphore(int value){ semaphore_p retval = (semaphore_p)calloc(1, sizeof(semaphore_t)); if(retval == NULL) return NULL; pthread_mutex_init(&retval->mutex, NULL); pthread_cond_init(&retval->cond, NULL); retval->value = (value >= 0) ? value : 0; return retval; } int postSemaphore(semaphore_p sem){ pthread_mutex_lock(&sem->mutex); /* illustrative example: don't worry about overflow */ sem->value++; pthread_cond_signal(&sem->cond); pthread_mutex_unlock(&sem->mutex); return 0; } int waitSemaphore(semaphore_p sem){ pthread_mutex_lock(&sem->mutex); while(sem->value == 0) pthread_cond_wait(&sem->cond, &sem->mutex); sem->value--; pthread_mutex_unlock(&sem->mutex); return 0; } void freeSemaphore(semaphore_p sem){ pthread_cond_destroy(&sem->cond); pthread_mutex_destroy(&sem->mutex); free(sem); }