#include #include "semaforo.h" int sem_init(sem_t *sem, int pshared, unsigned int value) { sem->c = value; sem->n_wait = 0; pthread_mutex_init(&sem->lock, NULL); pthread_cond_init(&sem->cond, NULL); return 0; } int sem_wait(sem_t * sem) { pthread_mutex_lock(&sem->lock); if (sem->c > 0) sem->c--; else { sem->n_wait++; pthread_cond_wait(&sem->cond, &sem->lock); } pthread_mutex_unlock(&sem->lock); return 0; } int sem_trywait(sem_t * sem) { pthread_mutex_lock(&sem->lock); if (sem->c > 0) { sem->c--; pthread_mutex_unlock(&sem->lock); return 0; /* Sucesso */ } else { pthread_mutex_unlock(&sem->lock); return -1; /* Insucesso */ } } int sem_post(sem_t * sem) { pthread_mutex_lock(&sem->lock); if (sem->n_wait > 0) { sem->n_wait--; pthread_cond_signal(&sem->cond); } else sem->c++; pthread_mutex_unlock(&sem->lock); return 0; } int sem_getvalue(sem_t * sem, int * sval) { pthread_mutex_lock(&sem->lock); *sval = sem->c; /* O que impediria c de ter um valor absurdo neste ponto? */ pthread_mutex_unlock(&sem->lock); return 0; } int sem_destroy(sem_t * sem) { pthread_mutex_destroy(&sem->lock); pthread_cond_destroy(&sem->cond); return 0; }