Potrzebuję stworzyć mapę bezpieczną dla wątków, gdzie mam na myśli to, że każda wartość musi być niezależnie muteksowana. Na przykład, muszę być w stanie uzyskać map["abc"]
i map["vf"]
w tym samym czasie z 2 różnych wątków.Mapa mutex C++ 11
Mój pomysł jest, aby dwie mapy: jeden dla danych i jeden dla mutex za każdy klucz:
class cache
{
private:
....
std::map<std::string, std::string> mainCache;
std::map<std::string, std::unique_ptr<std::mutex> > mutexCache;
std::mutex gMutex;
.....
public:
std::string get(std::string key);
};
std::string cache::get(std::string key){
std::mutex *m;
gMutex.lock();
if (mutexCache.count(key) == 0){
mutexCache.insert(new std::unique_ptr<std::mutex>);
}
m = mutexCache[key];
gMutex.unlock();
}
Uważam, że nie można stworzyć mapę ze sznurkiem do mutex, ponieważ nie ma konstruktora kopia w std::mutex
i muszę użyć std::unique_ptr
; ale gdy skompiluję to otrzymuję:
/home/user/test/cache.cpp:7: error: no matching function for call to 'std::map<std::basic_string<char>, std::unique_ptr<std::mutex> >::insert(std::unique_ptr<std::mutex>*)'
mutexCache.insert(new std::unique_ptr<std::mutex>);
^
Jak rozwiązać ten problem?
+1 dla 'std :: make_unique' –
FWIW, należy użyć 'make_unique' w C++ 11 też. –