elgcom elgcom - 4 months ago 44
C++ Question

thread safty of find() from a STL container of std::unique_ptr

Example code.

class Obj
void doSome(void)
std::cout << "Hello World!" << std::endl;

std::unordered_map<int, std::unique_ptr<Obj>> map;

// insert -- done with single thread and before find()
map[123] = std::move( std::unique_ptr<Obj>(new Obj) );

// find -- run from multiple threads
auto search = map.find(123); // <=== (Q)
if (search != map.end())


How about the thread safty if there are multiple threads running //find section with map.find(123)?

will map.find(123) always find the obj in every thread? as long as the search->second not assigned to someone else?


Neither find(), nor any other method in the unordered map is thread safe. If it's possible for one execution thread to call find() while any other thread calls any unordered map method that modifies it, this results in undefined behavior.

If multiple execution threads are calling find() with the same key, provided that there is no undefined behavior all execution threads will get the same value for that key.