-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrunloop.cpp
65 lines (52 loc) · 1.05 KB
/
runloop.cpp
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
#include <runloop.hpp>
#include <unistd.h>
#include <fcntl.h>
class Runloop::Impl {
public:
Impl() {
pipe(_pipe);
fcntl(_pipe[0], F_SETFL, O_NONBLOCK);
}
void wait() {
char c;
while (read(_pipe[0], &c, 1) > 0);
}
void wake() {
write(_pipe[1], "*", 1);
}
private:
int _pipe[2]{0};
};
Runloop::Runloop() : _impl(std::make_unique<Runloop::Impl>()) {
current().set(this);
}
Runloop::~Runloop() {
current().set(nullptr);
}
void Runloop::run() {
_running = true;
while (_running) {
{
std::lock_guard<std::recursive_mutex> lock(mutex);
while (!_queue.empty()) {
_queue.front()();
_queue.pop();
}
}
_impl->wait();
}
}
void Runloop::stop() {
invoke([this] {
_running = false;
wake();
});
}
void Runloop::invoke(WorkTask &&fn) {
std::lock_guard<std::recursive_mutex> lock(mutex);
_queue.push(std::move(fn));
wake();
}
void Runloop::wake() {
_impl->wake();
}