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_cond_init(&mutex->cond, &cond);
77 ret = pthread_mutex_init(&mutex->lock, &attr);
79 log_err("pthread_mutex_init: %s\n", strerror(ret));
86 fio_mutex_remove(mutex);
92 int fio_mutex_down_timeout(struct fio_mutex *mutex, unsigned int seconds)
97 clock_gettime(CLOCK_REALTIME, &t);
100 pthread_mutex_lock(&mutex->lock);
102 while (!mutex->value && !ret) {
104 ret = pthread_cond_timedwait(&mutex->cond, &mutex->lock, &t);
110 pthread_mutex_unlock(&mutex->lock);
116 void fio_mutex_down(struct fio_mutex *mutex)
118 pthread_mutex_lock(&mutex->lock);
120 while (!mutex->value) {
122 pthread_cond_wait(&mutex->cond, &mutex->lock);
127 pthread_mutex_unlock(&mutex->lock);
130 void fio_mutex_up(struct fio_mutex *mutex)
132 pthread_mutex_lock(&mutex->lock);
134 if (!mutex->value && mutex->waiters)
135 pthread_cond_signal(&mutex->cond);
137 pthread_mutex_unlock(&mutex->lock);
140 void fio_mutex_down_write(struct fio_mutex *mutex)
142 pthread_mutex_lock(&mutex->lock);
144 while (mutex->value != 0) {
146 pthread_cond_wait(&mutex->cond, &mutex->lock);
151 pthread_mutex_unlock(&mutex->lock);
154 void fio_mutex_down_read(struct fio_mutex *mutex)
156 pthread_mutex_lock(&mutex->lock);
158 while (mutex->value < 0) {
160 pthread_cond_wait(&mutex->cond, &mutex->lock);
165 pthread_mutex_unlock(&mutex->lock);
168 void fio_mutex_up_read(struct fio_mutex *mutex)
170 pthread_mutex_lock(&mutex->lock);
173 if (mutex->value >= 0 && mutex->waiters)
174 pthread_cond_signal(&mutex->cond);
175 pthread_mutex_unlock(&mutex->lock);
178 void fio_mutex_up_write(struct fio_mutex *mutex)
180 pthread_mutex_lock(&mutex->lock);
183 if (mutex->value >= 0 && mutex->waiters)
184 pthread_cond_signal(&mutex->cond);
185 pthread_mutex_unlock(&mutex->lock);