Merge branch 'master' of ssh://brick.kernel.dk/data/git/fio
[fio.git] / mutex.c
diff --git a/mutex.c b/mutex.c
index 1538f62c4b1a286ebe015c299031ffede126e2c4..34b3324ca7d395f49e1579390ba2f60322dd2ba1 100644 (file)
--- a/mutex.c
+++ b/mutex.c
@@ -3,6 +3,7 @@
 #include <unistd.h>
 #include <stdlib.h>
 #include <fcntl.h>
+#include <time.h>
 #include <pthread.h>
 #include <sys/mman.h>
 
@@ -71,6 +72,7 @@ struct fio_mutex *fio_mutex_init(int value)
 
        pthread_condattr_init(&cond);
        pthread_condattr_setpshared(&cond, mflag);
+       pthread_condattr_setclock(&cond, CLOCK_MONOTONIC);
        pthread_cond_init(&mutex->cond, &cond);
 
        ret = pthread_mutex_init(&mutex->lock, &attr);
@@ -88,6 +90,30 @@ err:
        return NULL;
 }
 
+int fio_mutex_down_timeout(struct fio_mutex *mutex, unsigned int seconds)
+{
+       struct timespec t;
+       int ret = 0;
+
+       clock_gettime(CLOCK_MONOTONIC, &t);
+       t.tv_sec += seconds;
+
+       pthread_mutex_lock(&mutex->lock);
+
+       while (!mutex->value && !ret) {
+               mutex->waiters++;
+               ret = pthread_cond_timedwait(&mutex->cond, &mutex->lock, &t);
+               mutex->waiters--;
+       }
+
+       if (!ret) {
+               mutex->value--;
+               pthread_mutex_unlock(&mutex->lock);
+       }
+
+       return ret;
+}
+
 void fio_mutex_down(struct fio_mutex *mutex)
 {
        pthread_mutex_lock(&mutex->lock);