From f090b30e587c7af51fde86f36c67ef139ed2ce6f Mon Sep 17 00:00:00 2001 From: LaG1924 <12997935+LaG1924@users.noreply.github.com> Date: Fri, 5 Jan 2018 18:12:13 +0300 Subject: Tried to fix deadlock --- src/Event.hpp | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) (limited to 'src/Event.hpp') diff --git a/src/Event.hpp b/src/Event.hpp index 752fda4..38541a1 100644 --- a/src/Event.hpp +++ b/src/Event.hpp @@ -63,8 +63,7 @@ class EventListener { using HandlerType = std::function; std::queue events; std::map handlers; - std::mutex eventsQueueMutex; - std::mutex handlersMutex; + std::recursive_mutex mutex; public: EventListener(); @@ -79,8 +78,9 @@ public: void WaitEvent(); void RegisterHandler(size_t eventId, const HandlerType &data) { - std::lock_guard lock(handlersMutex); + mutex.lock(); handlers[eventId] = data; + mutex.unlock(); } void RegisterHandler(const char *eventId, const HandlerType & data) { @@ -91,22 +91,25 @@ public: class EventSystem { friend class EventListener; static std::list listeners; - static std::mutex listenersMutex; + static std::recursive_mutex listenersMutex; public: template static void PushEvent(size_t eventId, T data) { Event event(eventId, data); - std::lock_guard listenersLock(listenersMutex); for (auto& listener : listeners) { - std::lock_guard lock(listener->eventsQueueMutex); - std::lock_guard lockHandlers(listener->handlersMutex); + //if (!listener->mutex.try_lock()) throw std::runtime_error("WHY?!"); + listener->mutex.lock(); auto it = listener->handlers.find(eventId); - if (it == listener->handlers.end()) - continue; + if (it == listener->handlers.end()) { + listener->mutex.unlock(); + continue; + } listener->events.push(event); + + listener->mutex.unlock(); } } @@ -114,16 +117,17 @@ public: static void DirectEventCall(size_t eventId, T data) { Event event(eventId, data); - std::lock_guard listenersLock(listenersMutex); + listenersMutex.lock(); for (auto & listener : listeners) { - std::lock_guard lock(listener->eventsQueueMutex); - std::lock_guard lockHandlers(listener->handlersMutex); + listener->mutex.lock(); auto it = listener->handlers.find(eventId); if (it == listener->handlers.end()) continue; it->second(event); + listener->mutex.unlock(); } + listenersMutex.unlock(); } }; -- cgit v1.2.3