xycs
xycs

Reputation: 131

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

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.

Upvotes: 1

Views: 300

Answers (2)

UpAndAdam
UpAndAdam

Reputation: 5467

You have to take the mutex for calling find so that no one can write to the map while your find call is executing. This goes for any non threadsafe container or structure, you have to protect it often from reading and writing simultaneously. Find is reading. It doesnt matter whether you are using std::find on a vector, a list, map, unordered_map, or somethign else. Unless the container is threadsafe you must provide the protection yourself.

Upvotes: 1

catnip
catnip

Reputation: 25388

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.

Upvotes: 2

Related Questions