#include "event.h" #include #include #include typedef enum SIGNAL_ { UNSIGNALED = 0, SIGNALED } SIGNAL; struct event_ { pthread_mutex_t lock; pthread_cond_t cond; SIGNAL signaled; }; event event_create() { event e; if ((e = malloc(sizeof(struct event_)))) { e->signaled = UNSIGNALED; if (0 == pthread_mutex_init(&e->lock, NULL)) { if (0 == pthread_cond_init(&e->cond, NULL)) return e; pthread_mutex_destroy(&e->lock); } free(e); } return NULL; } void event_destroy(event e) { assert(e); event_signal(e); pthread_mutex_lock(&e->lock); pthread_cond_destroy(&e->cond); pthread_mutex_unlock(&e->lock); pthread_mutex_destroy(&e->lock); free(e); } int event_wait(event e) { assert(e); pthread_mutex_lock(&e->lock); if (e->signaled == UNSIGNALED) pthread_cond_wait(&e->cond, &e->lock); pthread_mutex_unlock(&e->lock); sched_yield(); return 0; } void event_clear(event e) { assert(e); pthread_mutex_lock(&e->lock); e->signaled = UNSIGNALED; pthread_mutex_unlock(&e->lock); } void event_signal(event e) { assert(e); pthread_mutex_lock(&e->lock); e->signaled = SIGNALED; pthread_mutex_unlock(&e->lock); pthread_cond_broadcast(&e->cond); } void event_pulse(event e) { assert(e); pthread_mutex_lock(&e->lock); if (e->signaled == UNSIGNALED) { e->signaled = SIGNALED; pthread_cond_signal(&e->cond); pthread_mutex_unlock(&e->lock); sched_yield(); pthread_mutex_lock(&e->lock); e->signaled = UNSIGNALED; } pthread_mutex_unlock(&e->lock); } void event_pulse_all(event e) { assert(e); pthread_mutex_lock(&e->lock); if (e->signaled == UNSIGNALED) { e->signaled = SIGNALED; pthread_cond_broadcast(&e->cond); pthread_mutex_unlock(&e->lock); sched_yield(); pthread_mutex_lock(&e->lock); e->signaled = UNSIGNALED; } pthread_mutex_unlock(&e->lock); }