summaryrefslogtreecommitdiff
path: root/src/util.hpp
diff options
context:
space:
mode:
authorDan Goodliffe <dan@randomdan.homeip.net>2026-05-17 14:32:11 +0100
committerDan Goodliffe <dan@randomdan.homeip.net>2026-05-17 16:18:08 +0100
commit7b1aeee4565fe0a2eed4a4fa8695b2a5fb671e06 (patch)
tree1ea4e2565a8f8f57e85d27291810cad07cd3b6be /src/util.hpp
parent29f458117184af5b1507cac01b48b41bfbad568a (diff)
downloadwebstat-7b1aeee4565fe0a2eed4a4fa8695b2a5fb671e06.tar.bz2
webstat-7b1aeee4565fe0a2eed4a4fa8695b2a5fb671e06.tar.xz
webstat-7b1aeee4565fe0a2eed4a4fa8695b2a5fb671e06.zip
Add ThreadSafeT helper
Wraps a templated value and a templated mutex (defaults to shared_mutex) and provides safe access, locked with either a shared_lock (const value) or lock_guard (non-const value). Applies this to existingEntities.
Diffstat (limited to 'src/util.hpp')
-rw-r--r--src/util.hpp49
1 files changed, 49 insertions, 0 deletions
diff --git a/src/util.hpp b/src/util.hpp
index f7254e8..5cac5a3 100644
--- a/src/util.hpp
+++ b/src/util.hpp
@@ -3,6 +3,7 @@
#include <chrono>
#include <command.h>
#include <scn/scan.h>
+#include <shared_mutex>
#include <tuple>
namespace WebStat {
@@ -95,4 +96,52 @@ namespace WebStat {
}
return false;
}
+
+ template<typename ValueType, typename MutexType = std::shared_mutex> class ThreadSafeT {
+ public:
+ template<typename... P> ThreadSafeT(P &&... params) : value {std::forward<P>(params)...} { }
+
+ template<typename LockedValueType, typename LockType> class Locked {
+ public:
+ Locked(LockedValueType & valueRef, MutexType & mutex) : value {valueRef}, lock {mutex} { }
+
+ LockedValueType *
+ operator->()
+ {
+ return &value;
+ }
+
+ private:
+ LockedValueType & value;
+ LockType lock;
+ };
+
+ Locked<const ValueType, std::shared_lock<MutexType>>
+ shared() const
+ {
+ return {value, mutex};
+ }
+
+ Locked<ValueType, std::lock_guard<MutexType>>
+ unique()
+ {
+ return {value, mutex};
+ }
+
+ Locked<const ValueType, std::shared_lock<MutexType>>
+ operator->() const
+ {
+ return shared();
+ }
+
+ Locked<ValueType, std::lock_guard<MutexType>>
+ operator()()
+ {
+ return unique();
+ }
+
+ private:
+ ValueType value;
+ mutable MutexType mutex;
+ };
}