1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
|
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <pthread.h>
#include <errno.h>
#include "malloc.h"
#include "macro.h"
#include "mutex.h"
struct sa_mutex {
pthread_mutex_t mutex;
};
struct sa_cond {
pthread_cond_t cond;
};
sa_mutex* sa_mutex_new(sa_bool_t recursive, sa_bool_t inherit_priority) {
sa_mutex *m;
pthread_mutexattr_t attr;
int r;
sa_assert_se(pthread_mutexattr_init(&attr) == 0);
if (recursive)
sa_assert_se(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) == 0);
#ifdef HAVE_PTHREAD_PRIO_INHERIT
if (inherit_priority)
sa_assert_se(pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT) == 0);
#endif
if (!(m = sa_new(sa_mutex, 1)))
return NULL;
#ifndef HAVE_PTHREAD_PRIO_INHERIT
sa_assert_se(pthread_mutex_init(&m->mutex, &attr) == 0);
#else
if ((r = pthread_mutex_init(&m->mutex, &attr))) {
/* If this failed, then this was probably due to non-available
* priority inheritance. In which case we fall back to normal
* mutexes. */
sa_assert(r == ENOTSUP && inherit_priority);
sa_assert_se(pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_NONE) == 0);
sa_assert_se(pthread_mutex_init(&m->mutex, &attr) == 0);
}
#endif
return m;
}
void sa_mutex_free(sa_mutex *m) {
sa_assert(m);
sa_assert_se(pthread_mutex_destroy(&m->mutex) == 0);
sa_free(m);
}
void sa_mutex_lock(sa_mutex *m) {
sa_assert(m);
sa_assert_se(pthread_mutex_lock(&m->mutex) == 0);
}
void sa_mutex_unlock(sa_mutex *m) {
sa_assert(m);
sa_assert_se(pthread_mutex_unlock(&m->mutex) == 0);
}
sa_cond *sa_cond_new(void) {
sa_cond *c;
if (!(c = sa_new(sa_cond, 1)))
return NULL;
sa_assert_se(pthread_cond_init(&c->cond, NULL) == 0);
return c;
}
void sa_cond_free(sa_cond *c) {
sa_assert(c);
sa_assert_se(pthread_cond_destroy(&c->cond) == 0);
sa_free(c);
}
void sa_cond_signal(sa_cond *c, int broadcast) {
sa_assert(c);
if (broadcast)
sa_assert_se(pthread_cond_broadcast(&c->cond) == 0);
else
sa_assert_se(pthread_cond_signal(&c->cond) == 0);
}
int sa_cond_wait(sa_cond *c, sa_mutex *m) {
sa_assert(c);
sa_assert(m);
return pthread_cond_wait(&c->cond, &m->mutex);
}
|