Merge branch 'master' of https://github.com/bvanassche/fio
[fio.git] / pshared.c
1 #include <string.h>
2
3 #include "log.h"
4 #include "pshared.h"
5
6 int cond_init_pshared(pthread_cond_t *cond)
7 {
8         pthread_condattr_t cattr;
9         int ret;
10
11         ret = pthread_condattr_init(&cattr);
12         if (ret) {
13                 log_err("pthread_condattr_init: %s\n", strerror(ret));
14                 return ret;
15         }
16
17 #ifdef CONFIG_PSHARED
18         ret = pthread_condattr_setpshared(&cattr, PTHREAD_PROCESS_SHARED);
19         if (ret) {
20                 log_err("pthread_condattr_setpshared: %s\n", strerror(ret));
21                 return ret;
22         }
23 #endif
24
25 #ifdef CONFIG_PTHREAD_CONDATTR_SETCLOCK
26         ret = pthread_condattr_setclock(&cattr, CLOCK_MONOTONIC);
27         if (ret) {
28                 log_err("pthread_condattr_setclock: %s\n", strerror(ret));
29                 return ret;
30         }
31 #endif
32
33         ret = pthread_cond_init(cond, &cattr);
34         if (ret) {
35                 log_err("pthread_cond_init: %s\n", strerror(ret));
36                 return ret;
37         }
38
39         return 0;
40 }
41
42 /*
43  * 'type' must be a mutex type, e.g. PTHREAD_MUTEX_NORMAL,
44  * PTHREAD_MUTEX_ERRORCHECK, PTHREAD_MUTEX_RECURSIVE or PTHREAD_MUTEX_DEFAULT.
45  */
46 int mutex_init_pshared_with_type(pthread_mutex_t *mutex, int type)
47 {
48         pthread_mutexattr_t mattr;
49         int ret;
50
51         ret = pthread_mutexattr_init(&mattr);
52         if (ret) {
53                 log_err("pthread_mutexattr_init: %s\n", strerror(ret));
54                 return ret;
55         }
56
57         /*
58          * Not all platforms support process shared mutexes (NetBSD/OpenBSD)
59          */
60 #ifdef CONFIG_PSHARED
61         ret = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
62         if (ret) {
63                 log_err("pthread_mutexattr_setpshared: %s\n", strerror(ret));
64                 return ret;
65         }
66 #endif
67         ret = pthread_mutexattr_settype(&mattr, type);
68         if (ret) {
69                 log_err("pthread_mutexattr_settype: %s\n", strerror(ret));
70                 return ret;
71         }
72         ret = pthread_mutex_init(mutex, &mattr);
73         if (ret) {
74                 log_err("pthread_mutex_init: %s\n", strerror(ret));
75                 return ret;
76         }
77         pthread_mutexattr_destroy(&mattr);
78
79         return 0;
80 }
81
82 int mutex_init_pshared(pthread_mutex_t *mutex)
83 {
84         return mutex_init_pshared_with_type(mutex, PTHREAD_MUTEX_DEFAULT);
85 }
86
87 int mutex_cond_init_pshared(pthread_mutex_t *mutex, pthread_cond_t *cond)
88 {
89         int ret;
90
91         ret = mutex_init_pshared(mutex);
92         if (ret)
93                 return ret;
94
95         ret = cond_init_pshared(cond);
96         if (ret)
97                 return ret;
98
99         return 0;
100 }