-
Notifications
You must be signed in to change notification settings - Fork 3
/
channel.h
89 lines (68 loc) · 1.58 KB
/
channel.h
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
#ifndef CHANNEL_
#define CHANNEL_
#include <mutex>
#include <queue>
#include <thread>
#include <experimental/optional>
template <typename T>
class Channel {
public:
bool Send(T item) {
std::lock_guard<std::mutex> l(mu_);
// FIXME(an): Use maybe DCHECK from glog -> DCHECK(closed_)
if (closed_) {
return false;
}
list_.push(item);
cv_.notify_all();
return true;
}
std::experimental::optional<T> TryRecv() {
std::unique_lock<std::mutex> l(mu_);
cv_.wait(l, [&] { return list_.size() > 0 || closed_; });
if (list_.empty()) {
return {};
}
T entry = list_.front();
list_.pop();
return std::experimental::make_optional(entry);
}
void operator<<(T entry) { Send(entry); }
void Close() {
std::lock_guard<std::mutex> l(mu_);
cv_.notify_all();
closed_ = true;
}
bool Finished() {
std::lock_guard<std::mutex> l(mu_);
return closed_ && list_.empty();
}
class Iterator {
public:
explicit Iterator(Channel<T>* chan) : chan_(chan) {}
std::experimental::optional<T> operator*() {
return chan_->TryRecv();
}
void operator++() {
// does nothing on purpose since this
// iterator cannot advance.
}
bool operator!=(Iterator it) {
return !chan_->Finished();
}
private:
Channel<T>* chan_;
};
Iterator begin() {
return Iterator(this);
}
Iterator end() {
return Iterator(this);
}
private:
std::queue<T> list_;
std::mutex mu_;
std::condition_variable cv_;
bool closed_ = false;
};
#endif // CHANNEL_