12 #include "arch/arch.h"
16 void fio_mutex_remove(struct fio_mutex *mutex)
18 pthread_cond_destroy(&mutex->cond);
19 munmap((void *) mutex, sizeof(*mutex));
22 struct fio_mutex *fio_mutex_init(int value)
24 struct fio_mutex *mutex = NULL;
25 pthread_mutexattr_t attr;
26 pthread_condattr_t cond;
29 mutex = (void *) mmap(NULL, sizeof(struct fio_mutex),
30 PROT_READ | PROT_WRITE,
31 OS_MAP_ANON | MAP_SHARED, -1, 0);
32 if (mutex == MAP_FAILED) {
40 ret = pthread_mutexattr_init(&attr);
42 log_err("pthread_mutexattr_init: %s\n", strerror(ret));
47 * Not all platforms support process shared mutexes (FreeBSD)
49 #ifdef FIO_HAVE_PSHARED_MUTEX
50 ret = pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
52 log_err("pthread_mutexattr_setpshared: %s\n", strerror(ret));
57 pthread_condattr_init(&cond);
58 #ifdef FIO_HAVE_PSHARED_MUTEX
59 pthread_condattr_setpshared(&cond, PTHREAD_PROCESS_SHARED);
61 #ifdef FIO_HAVE_CLOCK_MONOTONIC
62 pthread_condattr_setclock(&cond, CLOCK_MONOTONIC);
64 pthread_condattr_setclock(&cond, CLOCK_REALTIME);
66 pthread_cond_init(&mutex->cond, &cond);
68 ret = pthread_mutex_init(&mutex->lock, &attr);
70 log_err("pthread_mutex_init: %s\n", strerror(ret));
74 pthread_condattr_destroy(&cond);
75 pthread_mutexattr_destroy(&attr);
80 fio_mutex_remove(mutex);
85 int fio_mutex_down_timeout(struct fio_mutex *mutex, unsigned int seconds)
90 #ifdef FIO_HAVE_CLOCK_MONOTONIC
91 clock_gettime(CLOCK_MONOTONIC, &t);
93 clock_gettime(CLOCK_REALTIME, &t);
97 pthread_mutex_lock(&mutex->lock);
99 while (!mutex->value && !ret) {
101 ret = pthread_cond_timedwait(&mutex->cond, &mutex->lock, &t);
107 pthread_mutex_unlock(&mutex->lock);
113 void fio_mutex_down(struct fio_mutex *mutex)
115 pthread_mutex_lock(&mutex->lock);
117 while (!mutex->value) {
119 pthread_cond_wait(&mutex->cond, &mutex->lock);
124 pthread_mutex_unlock(&mutex->lock);
127 void fio_mutex_up(struct fio_mutex *mutex)
129 pthread_mutex_lock(&mutex->lock);
131 if (!mutex->value && mutex->waiters)
132 pthread_cond_signal(&mutex->cond);
134 pthread_mutex_unlock(&mutex->lock);
137 void fio_mutex_down_write(struct fio_mutex *mutex)
139 pthread_mutex_lock(&mutex->lock);
141 while (mutex->value != 0) {
143 pthread_cond_wait(&mutex->cond, &mutex->lock);
148 pthread_mutex_unlock(&mutex->lock);
151 void fio_mutex_down_read(struct fio_mutex *mutex)
153 pthread_mutex_lock(&mutex->lock);
155 while (mutex->value < 0) {
157 pthread_cond_wait(&mutex->cond, &mutex->lock);
162 pthread_mutex_unlock(&mutex->lock);
165 void fio_mutex_up_read(struct fio_mutex *mutex)
167 pthread_mutex_lock(&mutex->lock);
170 if (mutex->value >= 0 && mutex->waiters)
171 pthread_cond_signal(&mutex->cond);
172 pthread_mutex_unlock(&mutex->lock);
175 void fio_mutex_up_write(struct fio_mutex *mutex)
177 pthread_mutex_lock(&mutex->lock);
180 if (mutex->value >= 0 && mutex->waiters)
181 pthread_cond_signal(&mutex->cond);
182 pthread_mutex_unlock(&mutex->lock);