simple-socket library 1.9.0
Loading...
Searching...
No Matches
EventHandler.h
Go to the documentation of this file.
1#ifndef NET_EventHandler_h__
2#define NET_EventHandler_h__
3
4#include <sys/epoll.h>
5
6#include <atomic>
7#include <chrono>
8#include <cstdint>
9#include <functional>
10#include <unordered_map>
11#include <vector>
12#include <deque>
13
14namespace NET
15{
16 // Single-threaded Linux epoll dispatcher.
17 // Owns only its internal epoll/eventfd and timerfd handles.
18 // Only stop() is cross-thread safe.
19 class EventHandler final
20 {
21 public:
22 using Events = std::uint32_t;
23 using Callback = std::function<void(int, Events)>;
24 using TimerId = std::uint64_t;
25 // For periodic timers, expirations can be >1 when the event loop falls behind.
26 using TimerCallback = std::function<void(std::uint64_t expirations)>;
27
28 enum Event : std::uint32_t
29 {
30 Read = EPOLLIN,
31 Write = EPOLLOUT,
32 Priority = EPOLLPRI,
33 PeerClosed = EPOLLRDHUP,
34 Error = EPOLLERR,
35 Hangup = EPOLLHUP
36 };
37
38 explicit EventHandler(int batchSize = 64);
39 ~EventHandler() noexcept;
40
41 EventHandler(const EventHandler&) = delete;
42 EventHandler& operator=(const EventHandler&) = delete;
44 EventHandler& operator=(EventHandler&&) = delete;
45
46 // The watched fd must remain open until remove(fd). Only the caller owns it.
47 // Call these from the event-loop thread, including from callbacks.
48 void add(int fd, Events interests, Callback callback);
49 void modify(int fd, Events interests);
50 void remove(int fd); // Idempotent, including inside callbacks.
51
52 // Owned timers (CLOCK_MONOTONIC); delay/interval must be positive.
53 // One-shot timers are removed automatically after their callback,
54 // unless rearmed during callback execution.
55 // Timer IDs are not file descriptors. Timer methods are event-loop-thread only.
56 TimerId addOneShotTimer(std::chrono::milliseconds delay, TimerCallback callback);
57 TimerId addPeriodicTimer(std::chrono::milliseconds interval, TimerCallback callback);
58
59 void restartTimer(TimerId id); // Reuse the most recently configured delay.
60 void restartTimer(TimerId id, std::chrono::milliseconds delay);
61 void removeTimer(TimerId id); // Idempotent, including inside callbacks.
62
63 // Queue an idle-phase callback (FIFO). Single-threaded, including callbacks.
64 // Deferred callbacks run after ready I/O/timers, not recursively. Callbacks
65 // deferred by another deferred callback run in a later wait() cycle.
66 // An eventfd write wakes epoll even if no external fd is ready.
67 void defer(std::function<void()> callback);
68
69 // Returns number of kernel notifications. A zero timeout always attempts epoll once.
70 // Negative timeout means wait indefinitely. EINTR does not extend the deadline.
71 int wait(int timeoutMs = -1);
72
73 // Keeps waiting for new events until stopped
74 void run();
75
76 // May be called from another thread to interrupt run()/wait(-1).
77 // Does not make registration or timer methods thread-safe.
78 void stop() noexcept;
79
80 // Explicitly allow a later run(). Call only after prior run()/wait() finishes,
81 // with no concurrent stop() request. All dispatch operations, including
82 // run(), wait(), and resetStop(), must remain on one thread; do not nest them.
83 void resetStop();
84
85 private:
86 struct Registration { int fd; Callback callback; };
87 struct Timer {
88 int fd;
89 TimerCallback callback;
90 std::chrono::milliseconds delay;
91 std::chrono::milliseconds interval;
92 std::uint64_t version = 0;
93 };
94
95 TimerId addTimer(std::chrono::milliseconds delay,
96 std::chrono::milliseconds interval,
97 TimerCallback callback);
98 void dispatchTimer(TimerId id);
99 void dispatchDeferred();
100
101 std::uint64_t drainEvent(int fd);
102 void signalEvent(int fd) noexcept;
103
104 int m_epollFd = -1;
105 int m_wakeFd = -1;
106 std::vector<epoll_event> m_ready;
107 std::uint64_t m_nextToken = 1;
108 TimerId m_nextTimerId = 1;
109
110 std::unordered_map<std::uint64_t, Registration> m_registrations;
111 std::unordered_map<int, std::uint64_t> m_byFd;
112 std::unordered_map<TimerId, Timer> m_timers;
113 std::deque<std::function<void()>> m_deferred;
114
115 std::atomic<bool> m_stopRequested{false};
116 std::atomic<bool> m_waiting{false};
117 };
118
119} // namespace NET
120
121#endif // NET_EventHandler_h__
void modify(int fd, Events interests)
void defer(std::function< void()> callback)
void removeTimer(TimerId id)
void add(int fd, Events interests, Callback callback)
void stop() noexcept
std::function< void(int, Events)> Callback
void restartTimer(TimerId id)
TimerId addOneShotTimer(std::chrono::milliseconds delay, TimerCallback callback)
void remove(int fd)
int wait(int timeoutMs=-1)
EventHandler(int batchSize=64)
std::function< void(std::uint64_t expirations)> TimerCallback
TimerId addPeriodicTimer(std::chrono::milliseconds interval, TimerCallback callback)
std::uint32_t Events
std::uint64_t TimerId
~EventHandler() noexcept