-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathEventLoop.h
More file actions
77 lines (59 loc) · 2.03 KB
/
EventLoop.h
File metadata and controls
77 lines (59 loc) · 2.03 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
// ===========================================================================
// EventLoop.h
// ===========================================================================
#pragma once
#include <iostream>
#include <condition_variable>
#include <functional>
#include <future>
#include <thread>
#include <mutex>
#include "../Logger/Logger.h"
class EventLoop
{
private:
using Event = std::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(const Event& callable);
void enqueue(Event&& callable) noexcept;
template<typename TFunc, typename ... TArgs>
void enqueueTask(TFunc&& callable, TArgs&& ...args)
{
Logger::log(std::cout, "enqueueTask ...");
{
std::lock_guard<std::mutex> guard{ m_mutex };
m_events.push_back([=] () mutable {
std::forward<TFunc>(callable) (std::forward<TArgs>(args) ...);
}
);
// more simpler, but not "perfect"
// m_events.push_back( [=] () mutable { callable (args ...); } );
// again more simpler, not "perfect", variables of capture clause explicitely listed
// m_events.push_back( [callable, args ... ] () mutable { callable (args ...); } );
}
m_condition.notify_one();
}
void start();
void stop();
private:
void threadProcedure();
};
// ===========================================================================
// End-of-File
// ===========================================================================