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);
62 ret = pthread_mutex_init(&mutex->lock, &attr);
64 log_err("pthread_mutex_init: %s\n", strerror(ret));
68 pthread_condattr_destroy(&cond);
69 pthread_mutexattr_destroy(&attr);
74 fio_mutex_remove(mutex);
79 int fio_mutex_down_timeout(struct fio_mutex *mutex, unsigned int seconds)
84 clock_gettime(CLOCK_REALTIME, &t);
87 pthread_mutex_lock(&mutex->lock);
89 while (!mutex->value && !ret) {
91 ret = pthread_cond_timedwait(&mutex->cond, &mutex->lock, &t);
97 pthread_mutex_unlock(&mutex->lock);
103 void fio_mutex_down(struct fio_mutex *mutex)
105 pthread_mutex_lock(&mutex->lock);
107 while (!mutex->value) {
109 pthread_cond_wait(&mutex->cond, &mutex->lock);
114 pthread_mutex_unlock(&mutex->lock);
117 void fio_mutex_up(struct fio_mutex *mutex)
119 pthread_mutex_lock(&mutex->lock);
121 if (!mutex->value && mutex->waiters)
122 pthread_cond_signal(&mutex->cond);
124 pthread_mutex_unlock(&mutex->lock);
127 void fio_mutex_down_write(struct fio_mutex *mutex)
129 pthread_mutex_lock(&mutex->lock);
131 while (mutex->value != 0) {
133 pthread_cond_wait(&mutex->cond, &mutex->lock);
138 pthread_mutex_unlock(&mutex->lock);
141 void fio_mutex_down_read(struct fio_mutex *mutex)
143 pthread_mutex_lock(&mutex->lock);
145 while (mutex->value < 0) {
147 pthread_cond_wait(&mutex->cond, &mutex->lock);
152 pthread_mutex_unlock(&mutex->lock);
155 void fio_mutex_up_read(struct fio_mutex *mutex)
157 pthread_mutex_lock(&mutex->lock);
160 if (mutex->value >= 0 && mutex->waiters)
161 pthread_cond_signal(&mutex->cond);
162 pthread_mutex_unlock(&mutex->lock);
165 void fio_mutex_up_write(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);