Search code examples
c++multithreadingconcurrencythread-safety

C++ unordered_map thread safety when inserting indepentent keys


C++ Container thread safety guidelines at http://en.cppreference.com/w/cpp/container#Thread_safety

say

  • Different elements in the same container can be modified concurrently by different threads

So my question is, let us say I have an unordered_map<MyKeyClass, MyValueClass> results and I have several threads running concurrently and populating this map upon completion with <unique_key, some_value>. It is guaranteed that each thread returns a unique MyKeyClass. Does that now mean that I can safely concurrently insert the values into results ?

If yes, then that answers my question.

If no, then how about I insert <key, empty_value> before spawning the threads and then there will be no concurrent insertions, just modifications of the values, which if I understand correctly should be ok ?


Solution

  • Does that now mean that I can safely concurrently insert the values into results ?

    No. A std::unordered_map is not inherently thread safe. You cannot modify it from different threads without adding synchronization.

    Modifying elements in a container can be done without modifying the container itself.

    If no, then how about I insert <key, empty_value> before spawning the threads and then there will be no concurrent insertions, just modifications of the values, which if I understand correctly should be ok ?

    Yes. The sentence you quote is about modifying elements in the container. It is not about inserting elements into a container. You cannot concurrently insert but modify elements.