Home > OS >  How to use find function on map/unordered_map in multi-thread programming
How to use find function on map/unordered_map in multi-thread programming

Time:01-26

I read somewhere saying find() is not thread safe on binary map STL 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() function 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.

CodePudding user response:

None of the standard library containers are threadsafe. If you want to do this kind of thing, you must protect all accesses (both read and write) by a mutex.

CodePudding user response:

You have to take the mutex for calling find so that no one can write to the map while your find call is executing.

  •  Tags:  
  • Related