ADD: added a simple threadsafe map class

This commit is contained in:
Henry Winkel
2023-01-04 21:15:29 +01:00
parent 5bb4cbbe1a
commit 38272e4af7
4 changed files with 162 additions and 0 deletions

View File

@@ -0,0 +1,97 @@
#pragma once
#include <mutex>
#include <map>
#include <condition_variable>
namespace SimCore {
template<typename K, typename V>
class SafeMap {
private:
std::map<K, V> store;
mutable std::mutex mx;
std::condition_variable c;
protected:
public:
SafeMap()
{
store = std::map<K, V>();
}
void addValue(K key, V value )
{
std::lock_guard<std::mutex> lock(mx);
store.emplace(key,value);
c.notify_one();
}
void removePair(K key)
{
std::lock_guard<std::mutex> lock(mx);
auto search = store.find(key);
if (search != store.end()) {
search = store.erase(search);
}
c.notify_one();
}
void overRideValue(K key, V newValue)
{
std::lock_guard<std::mutex> lock(mx);
auto search = store.find(key);
if (search != store.end()) {
store[key] = newValue;
}
c.notify_one();
}
V getValue(K key)
{
std::lock_guard<std::mutex> lock(mx);
V value;
auto search = store.find(key);
if (search != store.end()) {
value = store[key];
}
return value;
}
bool hasKey(K key)
{
std::lock_guard<std::mutex> lock(mx);
auto search = store.find(key);
if (search != store.end()) {
return true;
}else {
return false;
}
}
long size()
{
std::lock_guard<std::mutex> lock(std::mutex);
return store.size();
}
};
}