-
Notifications
You must be signed in to change notification settings - Fork 1
/
CondMutex.hpp
139 lines (115 loc) · 2.4 KB
/
CondMutex.hpp
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#pragma once
#include "decl.hxx"
#include "err.hpp"
#include "MutexGuard.hpp"
namespace cornus {
class CondMutex {
public:
mutable pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
mutable pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
union Data {
char *ptr;
struct {
bool act = false;
bool exit = false;
};
} data;
inline void Broadcast() {
pthread_cond_broadcast(&cond);
}
inline int CondWait() {
return pthread_cond_wait(&cond, &mutex);
}
MutexGuard guard(const Lock l = Lock::Yes) const {
return (l == Lock::Yes) ? MutexGuard(&mutex) : MutexGuard();
}
inline bool Lock(const enum Lock l = Lock::Yes)
{
if (l != Lock::Yes)
return true;
cint status = pthread_mutex_lock(&mutex);
return (status == 0);
}
inline bool TryLock() {
cint status = pthread_mutex_trylock(&mutex);
return (status == 0);
}
inline void Signal() {
pthread_cond_signal(&cond);
}
inline bool Unlock(const enum Lock l = Lock::Yes)
{
return (l != Lock::Yes) ? true : (pthread_mutex_unlock(&mutex) == 0);
}
void SetFlag(cbool b, const enum Lock l = Lock::Yes) {
Lock(l);
data.act = b;
Unlock(l);
}
bool GetFlag(const enum Lock l = Lock::Yes) {
Lock(l);
cbool b = data.act;
Unlock(l);
return b;
}
void SetPtr(char *p, const enum Lock l = Lock::Yes) {
Lock(l);
data.ptr = p;
Unlock(l);
}
char* GetPtr(const enum Lock l = Lock::Yes)
{
Lock(l);
char *p = data.ptr;
Unlock(l);
return p;
}
};
class Mutex {
public:
mutable pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
union Data {
char *ptr;
bool act;
} data;
MutexGuard guard(const enum Lock l = Lock::Yes) const {
return (l == Lock::Yes) ? MutexGuard(&mutex) : MutexGuard();
}
inline bool TryLock() {
return (pthread_mutex_trylock(&mutex) == 0);
}
inline bool Lock(const enum Lock l = Lock::Yes) {
if (l != Lock::Yes)
return true;
cint status = pthread_mutex_lock(&mutex);
return (status == 0);
}
inline bool Unlock(const enum Lock l = Lock::Yes) {
if (l != Lock::Yes)
return true;
return (pthread_mutex_unlock(&mutex) == 0);
}
void SetFlag(cbool b) {
Lock();
data.act = b;
Unlock();
}
bool GetFlag(const enum Lock l = Lock::Yes) {
Lock(l);
cbool b = data.act;
Unlock(l);
return b;
}
void SetPtr(char *p) {
Lock();
data.ptr = p;
Unlock();
}
char* GetPtr() {
Lock();
char *p = data.ptr;
Unlock();
return p;
}
};
} // cornus::