-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathEventLoop.cpp
More file actions
93 lines (68 loc) · 1.89 KB
/
EventLoop.cpp
File metadata and controls
93 lines (68 loc) · 1.89 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
// ===========================================================================
// EventLoop.cpp
// ===========================================================================
#include "EventLoop.h"
// default c'tor
EventLoop::EventLoop() : m_running{ false } {}
// d'tor
EventLoop::~EventLoop()
{
stop();
}
void EventLoop::start()
{
m_running = true;
m_thread = std::jthread { &EventLoop::threadProcedure, this };
}
void EventLoop::stop()
{
if (m_thread.joinable()) {
enqueue([this] { m_running = false; });
m_thread.join();
}
}
void EventLoop::threadProcedure()
{
Logger::log(std::cout, "> Event Loop");
std::vector<Event> events;
while (m_running)
{
{
std::unique_lock<std::mutex> guard{ m_mutex };
m_condition.wait(
guard,
[this] () -> bool { return ! m_events.empty(); }
);
if (!m_events.empty()) {
std::swap(events, m_events);
}
}
Logger::log(std::cout, "swapped ", events.size(), " event(s) ...");
for (const Event& callable : events)
{
Logger::log(std::cout, "! invoking next event");
callable();
}
events.clear(); // empty container for next loop
}
Logger::log(std::cout, "< Event Loop");
}
void EventLoop::enqueue(const Event& callable)
{
{
std::lock_guard<std::mutex> guard{ m_mutex };
m_events.push_back(callable);
}
m_condition.notify_one();
}
void EventLoop::enqueue(Event&& callable) noexcept
{
{
std::lock_guard<std::mutex> guard{ m_mutex };
m_events.push_back(std::move(callable));
}
m_condition.notify_one();
}
// ===========================================================================
// End-of-File
// ===========================================================================