-
Notifications
You must be signed in to change notification settings - Fork 2
/
Channel.h
59 lines (52 loc) · 1.23 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
#ifndef TRIPPIN_CHANNEL_H
#define TRIPPIN_CHANNEL_H
#include <queue>
#include <optional>
#include <mutex>
#include <condition_variable>
namespace trippin {
template<class T>
class Channel {
public:
std::optional<T> take() {
std::unique_lock lock(mutex);
cv.wait(lock, [this] { return closed || !queue.empty(); });
if (closed) {
return {};
}
auto e = queue.front();
queue.pop();
return e;
}
bool put(const T &elem) {
{
std::lock_guard lock(mutex);
if (closed) {
return false;
}
queue.push(elem);
}
cv.notify_one();
return true;
}
void close() {
{
std::unique_lock lk(mutex);
closed = true;
}
cv.notify_all();
}
int size() {
{
std::lock_guard lock(mutex);
return queue.size();
}
}
private:
std::queue<T> queue;
std::mutex mutex;
std::condition_variable cv;
bool closed{};
};
}
#endif