From fb5041a69d0f264176b537926c1922abfc295c33 Mon Sep 17 00:00:00 2001 From: Michael Fabian 'Xaymar' Dirks Date: Fri, 14 Feb 2020 07:28:57 +0100 Subject: [PATCH] util-event: Ensure thread safety --- source/util-event.hpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/source/util-event.hpp b/source/util-event.hpp index 069fb805..09160296 100644 --- a/source/util-event.hpp +++ b/source/util-event.hpp @@ -20,11 +20,13 @@ #pragma once #include #include +#include namespace util { template class event { std::list> listeners; + std::recursive_mutex lock; std::function listen_cb; std::function silence_cb; @@ -34,12 +36,14 @@ namespace util { // Destructor virtual ~event() { + std::lock_guard lock; this->clear(); } // Add new listener. inline void add(std::function listener) { + std::lock_guard lock; if (listeners.size() == 0) { if (listen_cb) { listen_cb(); @@ -51,6 +55,7 @@ namespace util { // Remove existing listener. inline void remove(std::function listener) { + std::lock_guard lock; listeners.remove(listener); if (listeners.size() == 0) { if (silence_cb) { @@ -62,12 +67,14 @@ namespace util { // Check if empty / no listeners. inline bool empty() { + std::lock_guard lock; return listeners.empty(); } // Remove all listeners. inline void clear() { + std::lock_guard lock; listeners.clear(); if (silence_cb) { silence_cb(); @@ -80,6 +87,7 @@ namespace util { template inline void operator()(_args... args) { + std::lock_guard lock; for (auto& l : listeners) { l(args...); } @@ -108,11 +116,13 @@ namespace util { public /* events */: void set_listen_callback(std::function cb) { + std::lock_guard lock; this->listen_cb = cb; } void set_silence_callback(std::function cb) { + std::lock_guard lock; this->silence_cb = cb; } };