-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathInputThread.h
84 lines (73 loc) · 2.09 KB
/
InputThread.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
#ifndef GOBAN_INPUTTHREAD_H
#define GOBAN_INPUTTHREAD_H
#include <mutex>
#include <deque>
#include <thread>
#include <iostream>
#include <condition_variable>
#include <string>
#include <chrono>
#include <spdlog/spdlog.h>
//based on https://gist.github.com/vmrob/ff20420a20c59b5a98a1
template <class C, class T>
class InputThread {
public:
InputThread(T &fin) : io(0) {
io = new std::thread([&]() {
std::string tmp;
bool good = true;
while (good) {
good = static_cast<bool>(std::getline(fin, tmp));
std::lock_guard<std::mutex> lock{mutex};
lines.push_back(std::move(tmp));
cv.notify_one();
}
lines.push_back("__EOF__");
cv.notify_one();
});
}
~InputThread() {
if(io) {
io->join();
delete io;
}
if(consumer) {
consumer->join();
delete consumer;
}
}
void bind(C &callback) {
consumer = new std::thread([&]() {
bool good = true;
while (good) {
{
std::unique_lock<std::mutex> lock{mutex};
if (cv.wait_for(lock, std::chrono::seconds(0), [&] { return !lines.empty(); })) {
std::swap(lines, toProcess);
}
}
if (!toProcess.empty()) {
for (auto &&line : toProcess) {
if(line != "__EOF__") {
callback(line);
}
else {
good = false;
break;
}
}
toProcess.clear();
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
});
}
private:
std::condition_variable cv;
std::mutex mutex;
std::deque<std::string> lines;
std::thread* io;
std::thread* consumer;
std::deque<std::string> toProcess;
};
#endif