-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchannel.h
More file actions
399 lines (336 loc) · 11.6 KB
/
channel.h
File metadata and controls
399 lines (336 loc) · 11.6 KB
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
#include <deque>
#include <functional>
#include <future>
#include <iostream>
#include <list>
#include <map>
#include <set>
#include <vector>
#include <any>
#include <queue>
using namespace std::chrono_literals;
#ifdef NDEBUG
#define LOG(...) void(0)
#else
#define LOG printf
#endif
namespace Channel {
class Select;
class Chan;
enum METHOD { READ, WRITE };
using Task = std::function<bool(const std::string &, const std::string &, const std::any&)>;
using Status = std::vector<std::tuple<Select *, METHOD, Chan *>>;
using NamedStatus = std::set<std::tuple<std::string, METHOD, std::string>>;
struct Command {
Channel::Chan *pChan;
METHOD method;
std::any pVal;
};
class Case {
public:
Case() = default;
Case(const Case &case_) = default;
Case(Command&& command, Task pFunc) : mMethod(command.method),
mpChan(command.pChan),
mpVal(command.pVal),
mpFunc(pFunc) {}
private:
friend class Select;
void exec(const Select *pSelect);
bool tryExec(const Select *pSelect);
METHOD mMethod;
Chan *mpChan = nullptr;
std::any mpVal;
Task mpFunc;
};
using Default = Case;
class Select {
public:
Select(std::initializer_list<Case> caseVec);
template <typename... T> Select(const std::string &name, T... caseVec);
template <
typename T,
typename std::enable_if<
std::is_same_v<typename std::iterator_traits<T>::value_type, Case>,
void>::type * = nullptr>
Select(const std::string &name, T begin, T end);
private:
template <typename T> void doSelect(const std::string &name, T begin, T end);
void doSelect(const std::string &name, std::initializer_list<Case> caseVec);
friend class Case;
friend Status watchStatus(const std::vector<Chan *> &chanVec);
friend NamedStatus watchNamedStatus(const std::vector<Chan *> &chanVec);
friend void printStatus(const Status &status);
std::string mName;
std::map<Chan *, Case> mpChan2Case;
std::mutex mMutex;
std::condition_variable mCv;
Chan *mpChanTobeNotified{nullptr};
};
Command operator>>(Chan*pChan, std::any pVal) {
return Command{pChan, METHOD::READ, pVal};
}
Command operator<<(Chan*pChan, std::any pVal) {
return Command{pChan, METHOD::WRITE, pVal};
}
class Chan {
public:
Chan(const std::string &name = "") : mName(name) {};
Chan(int capacity, const std::string &name = "") : mCapacity(capacity), mName(name) {};
void doWrite(const Select *pSelect, std::any& val) {
std::unique_lock<std::mutex> lock(mMutex);
mPayload = val;
mCv.notify_one();
}
void doRead(const Select *pSelect, std::any& val) {
std::unique_lock<std::mutex> lock(mMutex);
mCv.wait(lock, [&] { return mPayload.has_value(); });
val.swap(mPayload);
mPayload.reset();
}
bool tryWrite(const Select *pSelect, std::any& val) {
std::unique_lock<std::mutex> lock(mMutex);
if (full()) {
return false;
}
mBuffer.emplace(val);
return true;
}
bool tryRead(const Select *pSelect, std::any& val) {
std::unique_lock<std::mutex> lock(mMutex);
if (empty()) {
return false;
}
val.swap(mBuffer.front());
mBuffer.pop();
return true;
}
void bufferPush() {
mBuffer.push(mPayload);
mPayload.reset();
}
void bufferPop() {
mPayload = mBuffer.front();
mBuffer.pop();
}
bool empty() const {
return mBuffer.size() == 0;
}
bool full() const {
return mBuffer.size() >= mCapacity;
}
bool isBuffered() const {
return mCapacity > 0;
}
void write(std::any val, Task fun) {
Select{mName, Case{this << val, fun}};
}
void read(std::any val, Task fun) {
Select{mName, Case{this >> val, fun}};
}
std::string getName() const {
return mName;
}
size_t getCapacity() const {
return mCapacity;
}
private:
friend class Case;
friend class Select;
friend Status watchStatus(const std::vector<Chan *> &chanVec);
friend NamedStatus watchNamedStatus(const std::vector<Chan *> &chanVec);
friend void printStatus(const Status &status);
std::string mName;
std::queue<std::any> mBuffer{};
int mCapacity{0};
std::any mPayload;
std::mutex mMutex; // protect mBuffer
std::condition_variable mCv;
std::list<std::pair<Select *, METHOD>> waitingSelectList;
};
struct Coordinator {
std::mutex mMutex;
};
Coordinator gCoordinator;
void Case::exec(const Select *pSelect) {
if (mMethod == READ) {
mpChan->doRead(pSelect, mpVal);
} else {
mpChan->doWrite(pSelect, mpVal);
}
mpFunc(pSelect->mName, mpChan->mName, mpVal);
}
bool Case::tryExec(const Select *pSelect) {
//bool flag = (mMethod == READ) ? mpChan->tryRead(pSelect, mpVal)
// : mpChan->tryWrite(pSelect, mpVal);
bool flag = false;
if (mMethod == READ) {
flag = mpChan->tryRead(pSelect, mpVal);
} else
flag = mpChan->tryWrite(pSelect, mpVal);
if (!flag) return false;
mpFunc(pSelect->mName, mpChan->mName, mpVal);
return true;
}
template <typename... T> Select::Select(const std::string &name, T... caseVec) {
doSelect(name, {caseVec...});
}
Select::Select(std::initializer_list<Case> caseVec) {
doSelect("", caseVec.begin(), caseVec.end());
}
template <
typename T,
typename std::enable_if<
std::is_same_v<typename std::iterator_traits<T>::value_type, Case>,
void>::type *>
Select::Select(const std::string &name, T begin, T end) {
doSelect(name, begin, end);
}
void Select::doSelect(const std::string &name,
std::initializer_list<Case> caseVec) {
doSelect(name, caseVec.begin(), caseVec.end());
}
template <typename T>
void Select::doSelect(const std::string &name, T begin, T end) {
this->mName = name;
bool hasDefault = false;
for (auto it = begin; it != end; it++) {
auto &case_ = *it;
if (case_.mpChan==nullptr) {
if (it != end -1) throw std::runtime_error("default must be at the end");
hasDefault = true;
continue;
}
if (mpChan2Case.find(case_.mpChan) != mpChan2Case.end()) {
throw std::runtime_error("duplicated chan in same select");
}
mpChan2Case[case_.mpChan] = case_;
}
Select *pSelect = nullptr;
Case *pCase = nullptr;
bool hasWaiter = false;
{
std::unique_lock<std::mutex> gLock(gCoordinator.mMutex);
for (auto &pChan2CasePair : mpChan2Case) {
pCase = &pChan2CasePair.second;
Chan *pChan = pCase->mpChan;
if (pCase->mMethod == READ) {
if (!pChan->waitingSelectList.empty() &&
pChan->waitingSelectList.back().second == WRITE) {
pSelect = pChan->waitingSelectList.back()
.first; // remove blocked select
pChan->waitingSelectList.pop_back();
LOG("%s removed from %s's waiting list by %s\n", pSelect->mName.c_str(), pChan->mName.c_str(), this->mName.c_str());
hasWaiter = true;
break;
}
} else if (pCase->mMethod == WRITE) {
if (!pChan->waitingSelectList.empty() &&
pChan->waitingSelectList.front().second == READ) {
pSelect = pChan->waitingSelectList.front().first;
pChan->waitingSelectList.pop_front();
LOG("%s removed from %s's waiting list by %s\n", pSelect->mName.c_str(), pChan->mName.c_str(), this->mName.c_str());
hasWaiter = true;
break;
}
}
} // for
if (hasWaiter) {
// de-register peer
for (auto &pChan2CasePair : pSelect->mpChan2Case) {
Chan *pChan = pChan2CasePair.first;
pChan->waitingSelectList.remove_if(
[=](std::pair<Select *, METHOD> &a) {
LOG("%s removed from %s's waiting list\n", pSelect->mName.c_str(), pChan->mName.c_str());
return a.first == pSelect;
});
}
}
if (!hasWaiter) {
for (auto &pChan2CasePair : mpChan2Case) {
pCase = &pChan2CasePair.second;
Chan *pChan = pCase->mpChan;
if (pChan->isBuffered()) {
if (pCase->tryExec(this)) {
LOG("%s non block\n", this->mName.c_str());
return;
}
}
}
//not have buffered data
if (hasDefault) return;
// register self
for (auto &pChan2CasePair : mpChan2Case) {
auto &case_ = pChan2CasePair.second;
LOG("%s add into %s's waiting list\n", this->mName.c_str(), case_.mpChan->mName.c_str());
if (case_.mMethod == READ) {
case_.mpChan->waitingSelectList.emplace_front(this, READ);
} else {
case_.mpChan->waitingSelectList.emplace_back(this, WRITE);
}
}
}
} // gLock
if (hasWaiter) {
{
std::unique_lock<std::mutex> lock(pSelect->mMutex);
LOG("%s notify %s \n", this->mName.c_str(), pSelect->mName.c_str());
pSelect->mpChanTobeNotified = pCase->mpChan;
}
pSelect->mCv.notify_one();
pCase->exec(this);
return;
}
std::unique_lock<std::mutex> lock(mMutex);
mCv.wait(lock, [=]() {
return mpChanTobeNotified != nullptr;
});
LOG("%s notified\n", this->mName.c_str());
mpChan2Case[mpChanTobeNotified].exec(this);
}
Status watchStatus(const std::vector<Chan *> &chanVec) {
std::lock_guard<std::mutex>(gCoordinator.mMutex);
Status ret;
for (auto &pChan : chanVec) {
for (auto &[pSelect, method] : pChan->waitingSelectList) {
ret.emplace_back(pSelect, method, pChan);
}
}
return ret;
}
NamedStatus watchNamedStatus(const std::vector<Chan *> &chanVec) {
std::lock_guard<std::mutex>(gCoordinator.mMutex);
NamedStatus ret;
for (auto &pChan : chanVec) {
for (auto &[pSelect, method] : pChan->waitingSelectList) {
LOG("%s found in %s's waiting list\n", pSelect->mName.c_str(),
pChan->mName.c_str());
ret.insert(make_tuple(pSelect->mName, method, pChan->mName));
}
}
return ret;
}
void printStatus(const Status &status) {
printf("======================================\n");
for (auto &[pSelect, method, pChan] : status) {
printf("---%s\t%s\t%s---\n", pSelect->mName.c_str(),
method == METHOD::READ ? "read" : "write", pChan->mName.c_str());
}
printf("======================================\n");
}
void printNamedStatus(const NamedStatus &status) {
printf("======================================\n");
for (auto &[selectName, method, chanName] : status) {
printf("---%s\t%s\t%s---\n", selectName.c_str(),
method == METHOD::READ ? "read" : "write", chanName.c_str());
}
printf("======================================\n");
}
void printChannel(const std::vector<Channel::Chan *>& chanVec) {
printf("======================================\n");
for (Channel::Chan *chan : chanVec) {
printf("---%s\t%d---\n", chan->getName().c_str(), static_cast<int>(chan->getCapacity()));
}
printf("======================================\n");
}
} // namespace Channel