-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathEventLoop.h
More file actions
80 lines (63 loc) · 2.02 KB
/
EventLoop.h
File metadata and controls
80 lines (63 loc) · 2.02 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
// ===========================================================================
// EventLoop.h
// ===========================================================================
#pragma once
#include "../Logger/Logger.h"
#include <iostream>
#include <condition_variable>
#include <functional>
#include <future>
#include <thread>
#include <mutex>
class EventLoop
{
private:
using Event = std::move_only_function<void()>;
private:
std::vector<Event> m_events;
std::mutex m_mutex;
std::condition_variable m_condition;
std::jthread m_thread;
bool m_running;
public:
// c'tor(s) / d'tor
EventLoop();
~EventLoop();
// prevent copy semantics
EventLoop(const EventLoop&) = delete;
EventLoop& operator= (const EventLoop&) = delete;
// prevent move semantics
EventLoop(EventLoop&&) noexcept = delete;
EventLoop& operator= (EventLoop&&) noexcept = delete;
// public interface
void enqueue(Event callable);
template <typename TFunc>
void enqueue(TFunc&& func) {
m_events.emplace_back(std::forward<TFunc>(func));
}
template<typename TFunc, typename ... TArgs>
void enqueueTask(TFunc&& func, TArgs&& ...args)
{
Logger::log(std::cout, "enqueueTask ...");
// using "Generalized Lambda Capture" to preserve move semantics
auto callable {
[func = std::forward<TFunc>(func),
... capturedArgs = std::forward<TArgs>(args)] () {
std::invoke(std::move(func), std::move(capturedArgs) ...);
}
};
{
// RAII guard
std::lock_guard<std::mutex> guard{ m_mutex };
m_events.push_back(std::move(callable));
}
m_condition.notify_one();
}
void start();
void stop();
private:
void threadProcedure();
};
// ===========================================================================
// End-of-File
// ===========================================================================