-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Event.hxx
113 lines (81 loc) · 1.95 KB
/
Event.hxx
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#pragma once
#include <functional>
#include <mutex>
#include <set>
#include <vector>
namespace lli {
class EventListener;
class EventBase {
public:
virtual void Detach(EventListener *listener) = 0;
};
class EventListener
{
private:
std::set<EventBase*> events;
std::mutex events_mutex;
public:
~EventListener()
{
std::unique_lock<std::mutex> lock(events_mutex);
while (!events.empty())
{
auto e = *events.begin();
e->Detach(this);
}
}
void AddEvent(EventBase* event)
{
std::unique_lock<std::mutex> lock(events_mutex);
events.insert(event);
}
void RemoveEvent(EventBase* event)
{
events.erase(event);
}
};
template <typename... Args>
class Event : public EventBase
{
private:
class Handler
{
public:
EventListener *listener;
std::function<void(Args...)> func;
Handler(EventListener* listener, std::function<void(Args...)> func)
:
listener(listener),
func(func)
{
}
};
std::vector<Handler> handlers;
std::mutex handlers_mutex;
public:
void Attach(EventListener *listener, std::function<void(Args...)> func)
{
std::unique_lock<std::mutex> lock(handlers_mutex);
handlers.emplace_back(listener, func);
listener->AddEvent(this);
}
virtual void Detach(EventListener *listener) override
{
std::unique_lock<std::mutex> lock(handlers_mutex);
std::vector<Handler> h = handlers;
handlers.clear();
for (size_t i=0; i<h.size(); i++) {
if (h[i].listener != listener) {
handlers.push_back(h[i]);
}
}
listener->RemoveEvent(this);
}
void Dispatch(Args... args)
{
std::unique_lock<std::mutex> lock(handlers_mutex);
for (auto& handler : handlers)
handler.func(args...);
}
};
}