Skip to content

Instantly share code, notes, and snippets.

@yunusemreayhan
Created July 19, 2020 11:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yunusemreayhan/505e7c246a1d68c22ba5e6648a6ef992 to your computer and use it in GitHub Desktop.
Save yunusemreayhan/505e7c246a1d68c22ba5e6648a6ef992 to your computer and use it in GitHub Desktop.
Concurrent Map for c++
#pragma once
#include <mutex>
#include <map>
#include <functional>
#include <chrono>
template<class keyType, class dataType>
class ConcurrentMap {
std::map<keyType, dataType> dataMap;
std::timed_mutex ConcurrentMapLock;
public:
void insert(const std::pair<keyType, dataType> &toinsert) {
std::lock_guard<std::timed_mutex> lck(ConcurrentMapLock);
auto found = dataMap.find(toinsert.first);
if( found == dataMap.end()) {
dataMap.insert(toinsert);
}
}
void erase(keyType key) {
std::lock_guard<std::timed_mutex> lck(ConcurrentMapLock);
if(dataMap.find(key) != dataMap.end()) {
dataMap.erase(key);
}
}
int thread_safe_operation(
std::function<int(std::map<keyType, dataType>&)> thread_safe_fcall) {
std::lock_guard<std::timed_mutex> lck(ConcurrentMapLock);
int ret = thread_safe_fcall(dataMap);
return ret;
}
int thread_safe_operation_with_timeout(
std::function<int(std::map<keyType, dataType>&)> thread_safe_fcall,
std::chrono::milliseconds timeout) {
if(ConcurrentMapLock.try_lock_for(timeout)) {
std::lock_guard<std::timed_mutex> lck(ConcurrentMapLock, std::adopt_lock_t());
int ret = thread_safe_fcall(dataMap);
return ret;
}
return -1;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment