Created
July 19, 2020 11:15
-
-
Save yunusemreayhan/505e7c246a1d68c22ba5e6648a6ef992 to your computer and use it in GitHub Desktop.
Concurrent Map for c++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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