Search code examples
c++boostthread-safetyunordered-mapboost-unordered

Thread safety in boost::unordered_map of std::string and std::list, while making changes to list


I am using a boost::unordered_map<const std::string, std::list<TypeA> > in a performance critical multi-threaded environment. I understand that writing to STL containers isn't thread safe and the same goes for boost::unordered_map.

boost::unordered_map<const std::string, std::list<TypeA> > myMap;
// Added some elements to myMap        

Now, if I want to add or delete an element of type A to the list as , is it necessary is I just lock the entire map as opposed to locking the list that is being modified so that other threads can read/write the rest of the key value pairs?

// Assuming there are pair with the keys "Apple" and "Orange" in myMap
      A a, b;
      myMap["Orange"].push_back(a) //Add an element to the list
      myMap["Apple"].remove(b); //Remove an element 

What if the list is replaced by another STL container?

Thanks.


Solution

  • Since you're modifying only the contained object, not the [unordered_]map itself, you should only have to lock that contained object. If you change the list to another sequence (e.g., deque or vector) the same should remain true -- changing the type of the contained object doesn't change the fact that you're only modifying that contained object, not the map that contains it.