11 #include "arch/arch.h"
14 void fio_mutex_remove(struct fio_mutex *mutex)
16 close(mutex->mutex_fd);
17 munmap((void *) mutex, sizeof(*mutex));
20 struct fio_mutex *fio_mutex_init(int value)
22 char mutex_name[] = "/tmp/.fio_mutex.XXXXXX";
23 struct fio_mutex *mutex = NULL;
24 pthread_mutexattr_t attr;
25 pthread_condattr_t cond;
28 fd = mkstemp(mutex_name);
34 if (ftruncate(fd, sizeof(struct fio_mutex)) < 0) {
35 perror("ftruncate mutex");
39 mutex = (void *) mmap(NULL, sizeof(struct fio_mutex),
40 PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
41 if (mutex == MAP_FAILED) {
53 * Not all platforms support process shared mutexes (FreeBSD)
55 #ifdef FIO_HAVE_PSHARED_MUTEX
56 mflag = PTHREAD_PROCESS_SHARED;
58 mflag = PTHREAD_PROCESS_PRIVATE;
61 ret = pthread_mutexattr_init(&attr);
63 log_err("pthread_mutexattr_init: %s\n", strerror(ret));
66 ret = pthread_mutexattr_setpshared(&attr, mflag);
68 log_err("pthread_mutexattr_setpshared: %s\n", strerror(ret));
72 pthread_condattr_init(&cond);
73 pthread_condattr_setpshared(&cond, mflag);
74 pthread_cond_init(&mutex->cond, &cond);
76 ret = pthread_mutex_init(&mutex->lock, &attr);
78 log_err("pthread_mutex_init: %s\n", strerror(ret));
85 fio_mutex_remove(mutex);
91 void fio_mutex_down(struct fio_mutex *mutex)
93 pthread_mutex_lock(&mutex->lock);
95 while (!mutex->value) {
97 pthread_cond_wait(&mutex->cond, &mutex->lock);
102 pthread_mutex_unlock(&mutex->lock);
105 void fio_mutex_up(struct fio_mutex *mutex)
107 pthread_mutex_lock(&mutex->lock);
109 if (!mutex->value && mutex->waiters)
110 pthread_cond_signal(&mutex->cond);
112 pthread_mutex_unlock(&mutex->lock);
115 void fio_mutex_down_write(struct fio_mutex *mutex)
117 pthread_mutex_lock(&mutex->lock);
119 while (mutex->value != 0) {
121 pthread_cond_wait(&mutex->cond, &mutex->lock);
126 pthread_mutex_unlock(&mutex->lock);
129 void fio_mutex_down_read(struct fio_mutex *mutex)
131 pthread_mutex_lock(&mutex->lock);
133 while (mutex->value < 0) {
135 pthread_cond_wait(&mutex->cond, &mutex->lock);
140 pthread_mutex_unlock(&mutex->lock);
143 void fio_mutex_up_read(struct fio_mutex *mutex)
145 pthread_mutex_lock(&mutex->lock);
148 if (mutex->value >= 0 && mutex->waiters)
149 pthread_cond_signal(&mutex->cond);
150 pthread_mutex_unlock(&mutex->lock);
153 void fio_mutex_up_write(struct fio_mutex *mutex)
155 pthread_mutex_lock(&mutex->lock);
158 if (mutex->value >= 0 && mutex->waiters)
159 pthread_cond_signal(&mutex->cond);
160 pthread_mutex_unlock(&mutex->lock);