forked from seanbollin/reactor-proactor-example
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreactor.cpp
More file actions
97 lines (78 loc) · 2.04 KB
/
reactor.cpp
File metadata and controls
97 lines (78 loc) · 2.04 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
// Copyright 2017 Sean Bollin
#include <sys/epoll.h>
#include <unistd.h>
#include <iostream>
#include <array>
#include <limits>
#include <functional>
#include <unordered_map>
#include <string>
#include <utility>
class Epoll {
public:
static const int NO_FLAGS = 0;
static const int BLOCK_INDEFINITELY = -1;
static const int MAX_EVENTS = 1;
Epoll() {
fileDescriptor = epoll_create1(NO_FLAGS);
event.data.fd = STDIN_FILENO;
event.events = EPOLLIN | EPOLLPRI;
}
int control() {
return epoll_ctl(fileDescriptor, EPOLL_CTL_ADD, STDIN_FILENO, &event);
}
int wait() {
return epoll_wait(
fileDescriptor,
events.begin(),
MAX_EVENTS,
BLOCK_INDEFINITELY);
}
~Epoll() {
close(fileDescriptor);
}
private:
int fileDescriptor;
struct epoll_event event;
std::array<epoll_event, MAX_EVENTS> events{};
};
class Reactor {
public:
Reactor() {
epoll.control();
}
void addHandler(std::string event, std::function<void()> callback) {
handlers.emplace(std::move(event), std::move(callback));
}
void run() {
while (true) {
int numberOfEvents = wait();
for (int i = 0; i < numberOfEvents; ++i) {
std::string input;
std::getline(std::cin, input);
try {
handlers.at(input)();
} catch (const std::out_of_range& e) {
std::cout << "no handler for " << input << '\n';
}
}
}
}
private:
std::unordered_map<std::string, std::function<void()>> handlers{};
Epoll epoll;
int wait() {
int numberOfEvents = epoll.wait();
return numberOfEvents;
}
};
int main() {
Reactor reactor;
reactor.addHandler("one", [](){
std::cout << "one handler called!" << '\n';
});
reactor.addHandler("two", [](){
std::cout << "two handler called!" << '\n';
});
reactor.run();
}