diff --git a/lib/libimhex/include/hex/api/event.hpp b/lib/libimhex/include/hex/api/event.hpp index 07169446c..167edd8d3 100644 --- a/lib/libimhex/include/hex/api/event.hpp +++ b/lib/libimhex/include/hex/api/event.hpp @@ -91,6 +91,8 @@ namespace hex { */ template static EventList::iterator subscribe(typename E::Callback function) { + std::scoped_lock lock(getEventMutex()); + auto &events = getEvents(); return events.insert(events.end(), std::make_pair(E::Id, std::make_unique(function))); } @@ -103,6 +105,8 @@ namespace hex { */ template static void subscribe(void *token, typename E::Callback function) { + std::scoped_lock lock(getEventMutex()); + if (getTokenStore().contains(token)) { auto&& [begin, end] = getTokenStore().equal_range(token); auto eventRegistered = std::any_of(begin, end, [&](auto &item) { @@ -114,7 +118,7 @@ namespace hex { } } - getTokenStore().insert(std::make_pair(token, subscribe(function))); + getTokenStore().insert({ token, subscribe(function) }); } /** @@ -122,6 +126,8 @@ namespace hex { * @param token Token returned by subscribe */ static void unsubscribe(const EventList::iterator &token) noexcept { + std::scoped_lock lock(getEventMutex()); + getEvents().erase(token); } @@ -132,6 +138,8 @@ namespace hex { */ template static void unsubscribe(void *token) noexcept { + std::scoped_lock lock(getEventMutex()); + auto &tokenStore = getTokenStore(); auto iter = std::find_if(tokenStore.begin(), tokenStore.end(), [&](auto &item) { return item.first == token && item.second->first == E::Id; @@ -151,6 +159,8 @@ namespace hex { */ template static void post(auto &&...args) noexcept { + std::scoped_lock lock(getEventMutex()); + for (const auto &[id, event] : getEvents()) { if (id == E::Id) { (*static_cast(event.get()))(std::forward(args)...); @@ -167,6 +177,8 @@ namespace hex { * @brief Unsubscribe all subscribers from all events */ static void clear() noexcept { + std::scoped_lock lock(getEventMutex()); + getEvents().clear(); getTokenStore().clear(); } @@ -174,6 +186,7 @@ namespace hex { private: static std::multimap& getTokenStore(); static EventList& getEvents(); + static std::recursive_mutex& getEventMutex(); }; /* Default Events */ diff --git a/lib/libimhex/source/api/event.cpp b/lib/libimhex/source/api/event.cpp index a09a74c09..5d7194d19 100644 --- a/lib/libimhex/source/api/event.cpp +++ b/lib/libimhex/source/api/event.cpp @@ -14,5 +14,11 @@ namespace hex { return events; } + std::recursive_mutex& EventManager::getEventMutex() { + static std::recursive_mutex mutex; + + return mutex; + } + } \ No newline at end of file