#ifdef HAVE_CONFIG_H #include #endif #include #include #include "malloc.h" #include "macro.h" #include "mutex.h" struct sa_mutex { pthread_mutex_t mutex; }; struct sa_cond { pthread_cond_t cond; }; sa_mutex* sa_mutex_new(sa_bool_t recursive, sa_bool_t inherit_priority) { sa_mutex *m; pthread_mutexattr_t attr; int r; sa_assert_se(pthread_mutexattr_init(&attr) == 0); if (recursive) sa_assert_se(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) == 0); #ifdef HAVE_PTHREAD_PRIO_INHERIT if (inherit_priority) sa_assert_se(pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT) == 0); #endif if (!(m = sa_new(sa_mutex, 1))) return NULL; #ifndef HAVE_PTHREAD_PRIO_INHERIT sa_assert_se(pthread_mutex_init(&m->mutex, &attr) == 0); #else if ((r = pthread_mutex_init(&m->mutex, &attr))) { /* If this failed, then this was probably due to non-available * priority inheritance. In which case we fall back to normal * mutexes. */ sa_assert(r == ENOTSUP && inherit_priority); sa_assert_se(pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_NONE) == 0); sa_assert_se(pthread_mutex_init(&m->mutex, &attr) == 0); } #endif return m; } void sa_mutex_free(sa_mutex *m) { sa_assert(m); sa_assert_se(pthread_mutex_destroy(&m->mutex) == 0); sa_free(m); } void sa_mutex_lock(sa_mutex *m) { sa_assert(m); sa_assert_se(pthread_mutex_lock(&m->mutex) == 0); } void sa_mutex_unlock(sa_mutex *m) { sa_assert(m); sa_assert_se(pthread_mutex_unlock(&m->mutex) == 0); } sa_cond *sa_cond_new(void) { sa_cond *c; if (!(c = sa_new(sa_cond, 1))) return NULL; sa_assert_se(pthread_cond_init(&c->cond, NULL) == 0); return c; } void sa_cond_free(sa_cond *c) { sa_assert(c); sa_assert_se(pthread_cond_destroy(&c->cond) == 0); sa_free(c); } void sa_cond_signal(sa_cond *c, int broadcast) { sa_assert(c); if (broadcast) sa_assert_se(pthread_cond_broadcast(&c->cond) == 0); else sa_assert_se(pthread_cond_signal(&c->cond) == 0); } int sa_cond_wait(sa_cond *c, sa_mutex *m) { sa_assert(c); sa_assert(m); return pthread_cond_wait(&c->cond, &m->mutex); }