12 #include "arch/arch.h"
16 void fio_mutex_remove(struct fio_mutex *mutex)
18 close(mutex->mutex_fd);
19 munmap((void *) mutex, sizeof(*mutex));
22 struct fio_mutex *fio_mutex_init(int value)
24 char mutex_name[] = "/tmp/.fio_mutex.XXXXXX";
25 struct fio_mutex *mutex = NULL;
26 pthread_mutexattr_t attr;
27 pthread_condattr_t cond;
30 fd = mkstemp(mutex_name);
36 if (ftruncate(fd, sizeof(struct fio_mutex)) < 0) {
37 perror("ftruncate mutex");
41 mutex = (void *) mmap(NULL, sizeof(struct fio_mutex),
42 PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
43 if (mutex == MAP_FAILED) {
55 * Not all platforms support process shared mutexes (FreeBSD)
57 #ifdef FIO_HAVE_PSHARED_MUTEX
58 mflag = PTHREAD_PROCESS_SHARED;
60 mflag = PTHREAD_PROCESS_PRIVATE;
63 ret = pthread_mutexattr_init(&attr);
65 log_err("pthread_mutexattr_init: %s\n", strerror(ret));
68 #ifdef FIO_HAVE_PSHARED_MUTEX
69 ret = pthread_mutexattr_setpshared(&attr, mflag);
71 log_err("pthread_mutexattr_setpshared: %s\n", strerror(ret));
76 pthread_condattr_init(&cond);
77 #ifdef FIO_HAVE_PSHARED_MUTEX
78 pthread_condattr_setpshared(&cond, mflag);
80 pthread_cond_init(&mutex->cond, &cond);
82 ret = pthread_mutex_init(&mutex->lock, &attr);
84 log_err("pthread_mutex_init: %s\n", strerror(ret));
91 fio_mutex_remove(mutex);
97 int fio_mutex_down_timeout(struct fio_mutex *mutex, unsigned int seconds)
102 clock_gettime(CLOCK_REALTIME, &t);
105 pthread_mutex_lock(&mutex->lock);
107 while (!mutex->value && !ret) {
109 ret = pthread_cond_timedwait(&mutex->cond, &mutex->lock, &t);
115 pthread_mutex_unlock(&mutex->lock);
121 void fio_mutex_down(struct fio_mutex *mutex)
123 pthread_mutex_lock(&mutex->lock);
125 while (!mutex->value) {
127 pthread_cond_wait(&mutex->cond, &mutex->lock);
132 pthread_mutex_unlock(&mutex->lock);
135 void fio_mutex_up(struct fio_mutex *mutex)
137 pthread_mutex_lock(&mutex->lock);
139 if (!mutex->value && mutex->waiters)
140 pthread_cond_signal(&mutex->cond);
142 pthread_mutex_unlock(&mutex->lock);
145 void fio_mutex_down_write(struct fio_mutex *mutex)
147 pthread_mutex_lock(&mutex->lock);
149 while (mutex->value != 0) {
151 pthread_cond_wait(&mutex->cond, &mutex->lock);
156 pthread_mutex_unlock(&mutex->lock);
159 void fio_mutex_down_read(struct fio_mutex *mutex)
161 pthread_mutex_lock(&mutex->lock);
163 while (mutex->value < 0) {
165 pthread_cond_wait(&mutex->cond, &mutex->lock);
170 pthread_mutex_unlock(&mutex->lock);
173 void fio_mutex_up_read(struct fio_mutex *mutex)
175 pthread_mutex_lock(&mutex->lock);
178 if (mutex->value >= 0 && mutex->waiters)
179 pthread_cond_signal(&mutex->cond);
180 pthread_mutex_unlock(&mutex->lock);
183 void fio_mutex_up_write(struct fio_mutex *mutex)
185 pthread_mutex_lock(&mutex->lock);
188 if (mutex->value >= 0 && mutex->waiters)
189 pthread_cond_signal(&mutex->cond);
190 pthread_mutex_unlock(&mutex->lock);