From e970ba16827e6f4baf29004ccc1a48d378723f9e Mon Sep 17 00:00:00 2001 From: Albert S Date: Fri, 8 Oct 2021 00:08:00 +0200 Subject: [PATCH] cache: MapCache: Introduce MapCache, thread-safe cache (key/value store) --- cache/mapcache.cpp | 1 + cache/mapcache.h | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 cache/mapcache.cpp create mode 100644 cache/mapcache.h diff --git a/cache/mapcache.cpp b/cache/mapcache.cpp new file mode 100644 index 0000000..19eef95 --- /dev/null +++ b/cache/mapcache.cpp @@ -0,0 +1 @@ +#include "mapcache.h" diff --git a/cache/mapcache.h b/cache/mapcache.h new file mode 100644 index 0000000..4f0d00f --- /dev/null +++ b/cache/mapcache.h @@ -0,0 +1,37 @@ +#ifndef MAPCACHE_H +#define MAPCACHE_H +#include +#include +#include + +/* Thread-Safe Key-Value store */ +template class MapCache +{ + private: + std::map cache; + mutable std::shared_mutex sharedMutex; + + public: + std::optional find(const std::string &key) const + { + std::shared_lock lock(this->sharedMutex); + auto it = this->cache.find(key); + if(it != this->cache.end()) + { + return it->second; + } + return {}; + } + void set(const std::string &key, const T &val) + { + std::lock_guard lock{sharedMutex}; + this->cache[key] = val; + } + void clear() + { + std::lock_guard lock{sharedMutex}; + this->cache.clear(); + } +}; + +#endif // MAPCACHE_H