#include #include typedef struct semstruct semaphore; struct semstruct { int max; int val; // semaphore value pthread_mutex_t smutex; // proctects access to semaphore pthread_cond_t scond; // semaphore condition (val > 0) }; void semaphore_init(semaphore *sem, int max)// must do before given to threads! { sem->max = max; sem->val = sem->max; pthread_mutex_init(&(sem->smutex),NULL); pthread_cond_init(&(sem->scond),NULL); } // wait for semaphore (decrement) void proberen(semaphore *sem) { pthread_mutex_lock(&(sem->smutex)); while (sem->val < 1) pthread_cond_wait(&(sem->scond), &(sem->smutex)); sem->val -= 1; pthread_mutex_unlock(&(sem->smutex)); } // proberen // signal semaphore (increment) void verhogen(semaphore *sem) { pthread_mutex_lock(&(sem->smutex)); if (sem->val < sem->max) { sem->val += 1; pthread_cond_signal(&(sem->scond)); // wake someone up } // put it in ready state pthread_mutex_unlock(&(sem->smutex)); } // verhogen