I read somewhere saying find() is not thread safe on STL map because when other thread is inserting to the map, the map itself is re-balancing, so find() may not return the proper iterator even the entry is indeed in the map. My observation tends to echo this. How about hash map (unordered_map)? I fear it may have the same issue, but not clear why.
So what is the proper way to call find() in a multithreaded context or is there any replacement?
example can be:
std::map<int, std::string> the_map;
in thread 1:
// Step1
_mutex.lock();
the_map[1] = "this";
_mutex.unlock();
...
// Step3
if (the_map.find(1) == the_map.end()) {
throw("Cannot find!");
}
in thread 2
// Step2
_mutex.lock();
the_map[2] = "that";
_mutex.unlock();
If step 2 and 3 are taking places concurrently, then step 3 could be disrupted.