Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading