10 #include "arch/arch.h"
12 void fio_mutex_remove(struct fio_mutex *mutex)
14 close(mutex->mutex_fd);
15 munmap((void *) mutex, sizeof(*mutex));
18 struct fio_mutex *fio_mutex_init(int value)
20 char mutex_name[] = "/tmp/.fio_mutex.XXXXXX";
21 struct fio_mutex *mutex = NULL;
22 pthread_mutexattr_t attr;
23 pthread_condattr_t cond;
26 fd = mkstemp(mutex_name);
32 if (ftruncate(fd, sizeof(struct fio_mutex)) < 0) {
33 perror("ftruncate mutex");
37 mutex = (void *) mmap(NULL, sizeof(struct fio_mutex),
38 PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
39 if (mutex == MAP_FAILED) {
50 if (pthread_mutexattr_init(&attr) < 0) {
51 perror("pthread_mutexattr_init");
54 if (pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED) < 0) {
55 perror("pthread_mutexattr_setpshared");
59 pthread_condattr_init(&cond);
60 pthread_condattr_setpshared(&cond, PTHREAD_PROCESS_SHARED);
61 pthread_cond_init(&mutex->cond, &cond);
63 if (pthread_mutex_init(&mutex->lock, &attr) < 0) {
64 perror("pthread_mutex_init");
71 fio_mutex_remove(mutex);
77 void fio_mutex_down(struct fio_mutex *mutex)
79 pthread_mutex_lock(&mutex->lock);
81 while (!mutex->value) {
83 pthread_cond_wait(&mutex->cond, &mutex->lock);
88 pthread_mutex_unlock(&mutex->lock);
91 void fio_mutex_up(struct fio_mutex *mutex)
93 pthread_mutex_lock(&mutex->lock);
95 if (!mutex->value && mutex->waiters)
96 pthread_cond_signal(&mutex->cond);
98 pthread_mutex_unlock(&mutex->lock);
101 void fio_mutex_down_write(struct fio_mutex *mutex)
103 pthread_mutex_lock(&mutex->lock);
105 while (mutex->value != 0) {
107 pthread_cond_wait(&mutex->cond, &mutex->lock);
112 pthread_mutex_unlock(&mutex->lock);
115 void fio_mutex_down_read(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_up_read(struct fio_mutex *mutex)
131 pthread_mutex_lock(&mutex->lock);
134 if (mutex->value >= 0 && mutex->waiters)
135 pthread_cond_signal(&mutex->cond);
136 pthread_mutex_unlock(&mutex->lock);
139 void fio_mutex_up_write(struct fio_mutex *mutex)
141 pthread_mutex_lock(&mutex->lock);
144 if (mutex->value >= 0 && mutex->waiters)
145 pthread_cond_signal(&mutex->cond);
146 pthread_mutex_unlock(&mutex->lock);