qb  2.0.0.0
C++17 Actor Framework
qb Issue Watch Star Fork Follow @isndev
Loading...
Searching...
No Matches
epoll.h
Go to the documentation of this file.
1
26
27#include <exception>
29#include <sys/epoll.h>
30#include "../helper.h"
31
32#ifdef __WIN__SYSTEM__
33#error "epoll is not available on windows"
34#endif
35
36#ifndef QB_IO_EPOLL_H
37#define QB_IO_EPOLL_H
38
39namespace qb {
40namespace io {
41namespace epoll {
42
50class Proxy {
51protected:
52 int _epoll;
53
54public:
58 Proxy() = default;
59
64 Proxy(const int epoll)
65 : _epoll(epoll) {}
66
67public:
71 using item_type = epoll_event;
72
76 Proxy(Proxy const &) = default;
77
84 inline int
85 ctl(item_type &item) const {
86 return epoll_ctl(_epoll, EPOLL_CTL_MOD, item.data.fd, &item);
87 }
88
95 inline int
96 add(item_type &item) const {
97 return epoll_ctl(_epoll, EPOLL_CTL_ADD, item.data.fd, &item);
98 }
99
106 inline int
107 remove(item_type const &item) {
108 return epoll_ctl(_epoll, EPOLL_CTL_DEL, item.data.fd, nullptr);
109 }
110};
111
124template <std::size_t _MAX_EVENTS = 4096>
125class Poller : public Proxy {
126 epoll_event _epvts[_MAX_EVENTS];
127
128public:
136 : Proxy(epoll_create(_MAX_EVENTS)) {
137 if (unlikely(_epoll < 0))
138 throw std::runtime_error("failed to init epoll::Poller");
139 }
140
146 Poller(Poller const &) = delete;
147
154 ::close(_epoll);
155 }
156
168 template <typename _Func>
169 inline void
170 wait(_Func const &func, int const timeout = 0) {
171 const int ret = epoll_wait(_epoll, _epvts, _MAX_EVENTS, timeout);
172 if (unlikely(ret < 0)) {
173 std::cerr << "epoll::Poller polling has failed " << std::endl;
174 return;
175 }
176 for (int i = 0; i < ret; ++i) {
177 func(_epvts[i]);
178 }
179 }
180};
181
182} // namespace epoll
183} // namespace io
184} // namespace qb
185
186#endif // QB_IO_EPOLL_H
Branch prediction hint utilities for performance optimization.
Poller()
Constructor.
Definition epoll.h:135
Poller(Poller const &)=delete
Copy constructor (deleted)
void wait(_Func const &func, int const timeout=0)
Wait for events and process them.
Definition epoll.h:170
~Poller()
Destructor.
Definition epoll.h:153
epoll_event item_type
Type alias for epoll event item.
Definition epoll.h:71
Proxy()=default
Default constructor.
int ctl(item_type &item) const
Modify an existing file descriptor in the epoll set.
Definition epoll.h:85
int _epoll
The epoll file descriptor.
Definition epoll.h:52
int add(item_type &item) const
Add a new file descriptor to the epoll set.
Definition epoll.h:96
Proxy(const int epoll)
Constructor.
Definition epoll.h:64
int remove(item_type const &item)
Remove a file descriptor from the epoll set.
Definition epoll.h:107
Proxy(Proxy const &)=default
Copy constructor.
bool unlikely(bool expr)
Hint for branch prediction when a condition is expected to be false.
Definition branch_hints.h:76