12 #include "arch/arch.h"
15 void fio_mutex_remove(struct fio_mutex *mutex)
17 close(mutex->mutex_fd);
18 munmap((void *) mutex, sizeof(*mutex));
21 struct fio_mutex *fio_mutex_init(int value)
23 char mutex_name[] = "/tmp/.fio_mutex.XXXXXX";
24 struct fio_mutex *mutex = NULL;
25 pthread_mutexattr_t attr;
26 pthread_condattr_t cond;
29 fd = mkstemp(mutex_name);
35 if (ftruncate(fd, sizeof(struct fio_mutex)) < 0) {
36 perror("ftruncate mutex");
40 mutex = (void *) mmap(NULL, sizeof(struct fio_mutex),
41 PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
42 if (mutex == MAP_FAILED) {
54 * Not all platforms support process shared mutexes (FreeBSD)
56 #ifdef FIO_HAVE_PSHARED_MUTEX
57 mflag = PTHREAD_PROCESS_SHARED;
59 mflag = PTHREAD_PROCESS_PRIVATE;
62 ret = pthread_mutexattr_init(&attr);
64 log_err("pthread_mutexattr_init: %s\n", strerror(ret));
67 ret = pthread_mutexattr_setpshared(&attr, mflag);
69 log_err("pthread_mutexattr_setpshared: %s\n", strerror(ret));
73 pthread_condattr_init(&cond);
74 pthread_condattr_setpshared(&cond, mflag);
75 pthread_condattr_setclock(&cond, CLOCK_MONOTONIC);
76 pthread_cond_init(&mutex->cond, &cond);
78 ret = pthread_mutex_init(&mutex->lock, &attr);
80 log_err("pthread_mutex_init: %s\n", strerror(ret));
87 fio_mutex_remove(mutex);
93 int fio_mutex_down_timeout(struct fio_mutex *mutex, unsigned int seconds)
98 clock_gettime(CLOCK_MONOTONIC, &t);
101 pthread_mutex_lock(&mutex->lock);
103 while (!mutex->value && !ret) {
105 ret = pthread_cond_timedwait(&mutex->cond, &mutex->lock, &t);
111 pthread_mutex_unlock(&mutex->lock);
117 void fio_mutex_down(struct fio_mutex *mutex)
119 pthread_mutex_lock(&mutex->lock);
121 while (!mutex->value) {
123 pthread_cond_wait(&mutex->cond, &mutex->lock);
128 pthread_mutex_unlock(&mutex->lock);
131 void fio_mutex_up(struct fio_mutex *mutex)
133 pthread_mutex_lock(&mutex->lock);
135 if (!mutex->value && mutex->waiters)
136 pthread_cond_signal(&mutex->cond);
138 pthread_mutex_unlock(&mutex->lock);
141 void fio_mutex_down_write(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_down_read(struct fio_mutex *mutex)
157 pthread_mutex_lock(&mutex->lock);
159 while (mutex->value < 0) {
161 pthread_cond_wait(&mutex->cond, &mutex->lock);
166 pthread_mutex_unlock(&mutex->lock);
169 void fio_mutex_up_read(struct fio_mutex *mutex)
171 pthread_mutex_lock(&mutex->lock);
174 if (mutex->value >= 0 && mutex->waiters)
175 pthread_cond_signal(&mutex->cond);
176 pthread_mutex_unlock(&mutex->lock);
179 void fio_mutex_up_write(struct fio_mutex *mutex)
181 pthread_mutex_lock(&mutex->lock);
184 if (mutex->value >= 0 && mutex->waiters)
185 pthread_cond_signal(&mutex->cond);
186 pthread_mutex_unlock(&mutex->lock);