-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAsyncEventDispatcher.mpp
More file actions
51 lines (44 loc) · 1.47 KB
/
AsyncEventDispatcher.mpp
File metadata and controls
51 lines (44 loc) · 1.47 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
export module CppUtils.Thread.AsyncEventDispatcher;
import std;
import CppUtils.Execution.EventDispatcher;
import CppUtils.String.Hash;
import CppUtils.Thread.ThreadPool;
export namespace CppUtils::Thread
{
class AsyncEventDispatcher final
{
public:
explicit AsyncEventDispatcher(
std::size_t numberThreads = std::max(1uz, static_cast<std::size_t>(std::thread::hardware_concurrency())),
std::function<void(std::exception_ptr)> onError = nullptr,
std::function<void()> finally = nullptr):
m_threadPool{numberThreads, std::move(onError), std::move(finally)}
{}
template<String::Hasher eventName = Type::Hash{}, class... Args>
inline auto emit(const Args&... args) -> void
{
emit(static_cast<Type::Hash>(eventName), args...);
}
template<class... Args>
inline auto emit(Type::Hash eventName, Args&&... args) -> void
{
m_threadPool.call([this, eventName, payload = std::make_tuple(std::forward<Args>(args)...)]() mutable {
std::apply([this, eventName](auto&&... args) {
m_eventDispatcher.emit(eventName, std::forward<decltype(args)>(args)...);
}, std::move(payload));
});
}
template<String::Hasher eventName = Type::Hash{}>
inline auto subscribe(auto&& function) -> void
{
m_eventDispatcher.subscribe<eventName>(std::forward<decltype(function)>(function));
}
inline auto waitUntilFinished() -> void
{
m_threadPool.waitUntilFinished();
}
private:
ThreadPool m_threadPool;
Execution::EventDispatcher m_eventDispatcher;
};
}