-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathEventLoop.cpp
More file actions
82 lines (61 loc) · 1.74 KB
/
EventLoop.cpp
File metadata and controls
82 lines (61 loc) · 1.74 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
// ===========================================================================
// 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::enqueue(Event callable)
{
{
std::lock_guard<std::mutex> guard{ m_mutex };
m_events.push_back(std::move(callable));
}
m_condition.notify_one();
}
void EventLoop::threadProcedure()
{
Logger::log(std::cout, "> Event Loop");
std::vector<Event> events;
while (true)
{
{
std::unique_lock<std::mutex> guard{ m_mutex };
m_condition.wait(
guard,
[this] () -> bool { return ! m_events.empty() || !m_running; }
);
if (!m_running && m_events.empty()) {
Logger::log(std::cout, "< Event Loop");
return;
}
std::swap(events, m_events);
}
Logger::log(std::cout, "swapped ", events.size(), " event(s) ...");
for (auto& callable : events)
{
Logger::log(std::cout, "! invoking next event");
callable();
}
events.clear(); // empty container for next loop
}
}
// ===========================================================================
// End-of-File
// ===========================================================================