12 #include "arch/arch.h"
16 void fio_mutex_remove(struct fio_mutex *mutex)
18 munmap((void *) mutex, sizeof(*mutex));
21 struct fio_mutex *fio_mutex_init(int value)
23 struct fio_mutex *mutex = NULL;
24 pthread_mutexattr_t attr;
25 pthread_condattr_t cond;
28 mutex = (void *) mmap(NULL, sizeof(struct fio_mutex),
29 PROT_READ | PROT_WRITE,
30 OS_MAP_ANON | MAP_SHARED, -1, 0);
31 if (mutex == MAP_FAILED) {
39 ret = pthread_mutexattr_init(&attr);
41 log_err("pthread_mutexattr_init: %s\n", strerror(ret));
46 * Not all platforms support process shared mutexes (FreeBSD)
48 #ifdef FIO_HAVE_PSHARED_MUTEX
49 ret = pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
51 log_err("pthread_mutexattr_setpshared: %s\n", strerror(ret));
56 pthread_condattr_init(&cond);
57 #ifdef FIO_HAVE_PSHARED_MUTEX
58 pthread_condattr_setpshared(&cond, PTHREAD_PROCESS_SHARED);
60 pthread_cond_init(&mutex->cond, &cond);
61 #ifdef FIO_HAVE_CLOCK_MONOTONIC
62 pthread_condattr_setclock(&cond, CLOCK_MONOTONIC);
64 pthread_condattr_setclock(&cond, CLOCK_REALTIME);
67 ret = pthread_mutex_init(&mutex->lock, &attr);
69 log_err("pthread_mutex_init: %s\n", strerror(ret));
73 pthread_condattr_destroy(&cond);
74 pthread_mutexattr_destroy(&attr);
79 fio_mutex_remove(mutex);
84 int fio_mutex_down_timeout(struct fio_mutex *mutex, unsigned int seconds)
89 #ifdef FIO_HAVE_CLOCK_MONOTONIC
90 clock_gettime(CLOCK_MONOTONIC, &t);
92 clock_gettime(CLOCK_REALTIME, &t);
96 pthread_mutex_lock(&mutex->lock);
98 while (!mutex->value && !ret) {
100 ret = pthread_cond_timedwait(&mutex->cond, &mutex->lock, &t);
106 pthread_mutex_unlock(&mutex->lock);
112 void fio_mutex_down(struct fio_mutex *mutex)
114 pthread_mutex_lock(&mutex->lock);
116 while (!mutex->value) {
118 pthread_cond_wait(&mutex->cond, &mutex->lock);
123 pthread_mutex_unlock(&mutex->lock);
126 void fio_mutex_up(struct fio_mutex *mutex)
128 pthread_mutex_lock(&mutex->lock);
130 if (!mutex->value && mutex->waiters)
131 pthread_cond_signal(&mutex->cond);
133 pthread_mutex_unlock(&mutex->lock);
136 void fio_mutex_down_write(struct fio_mutex *mutex)
138 pthread_mutex_lock(&mutex->lock);
140 while (mutex->value != 0) {
142 pthread_cond_wait(&mutex->cond, &mutex->lock);
147 pthread_mutex_unlock(&mutex->lock);
150 void fio_mutex_down_read(struct fio_mutex *mutex)
152 pthread_mutex_lock(&mutex->lock);
154 while (mutex->value < 0) {
156 pthread_cond_wait(&mutex->cond, &mutex->lock);
161 pthread_mutex_unlock(&mutex->lock);
164 void fio_mutex_up_read(struct fio_mutex *mutex)
166 pthread_mutex_lock(&mutex->lock);
169 if (mutex->value >= 0 && mutex->waiters)
170 pthread_cond_signal(&mutex->cond);
171 pthread_mutex_unlock(&mutex->lock);
174 void fio_mutex_up_write(struct fio_mutex *mutex)
176 pthread_mutex_lock(&mutex->lock);
179 if (mutex->value >= 0 && mutex->waiters)
180 pthread_cond_signal(&mutex->cond);
181 pthread_mutex_unlock(&mutex->lock);