Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread-safety of reading and writing from/to std::map in C++

I have a multi-threaded application which uses shared data structure, which wraps std::map.

I know that STL is not thread-safe and it's my job to synchronize all threads. Also I think that inserting and removing elements from list doesn't invalidate the iterators to the other elements.

So I've got per-element locks in my code, which guards from the case 'two threads reading/writing to the same element. Let's that two threads work on two different objects. They hold locks for the objects so the other threads can't modify/remove their objects.

However 3rd thread at the same time tries to remove 3rd different object. She has acquired lock for it so no other thread will attempt to read write or remove it.

Is it thread-safe to remove element from map while other threads are reading/writing to other elements of the map?

like image 816
Tsvetomir Dimitrov Avatar asked Oct 13 '25 09:10

Tsvetomir Dimitrov


1 Answers

Please note that you knowledge that the STL containers are not thread-safe is wrong! In C++2011 the container provide reasonable thread-safety guarantees. They may be different from what you might wish for but they are reasonable and important:

  1. If there is not thread modifying the structure of the container, there can be concurrent threads which read the structure of the same container object.
  2. If there is a writer for the structure of a container, there shall be no other accesses to the container.
  3. Different objects are independent and concurrent access of different container objects doesn't require synchronization.

These guarantees mean that you don't need any synchronization for the container if multiple threads just access the container but don't change its structure. Since the elements are provided by the user they may need individual sychronization depending on theirown thread-safety guarantees. If there are threads modifying the structure of a container, it is necessary to properly synchronize the accesses.

For your case you have to make sure that no thread reads the map while the is some thread modifying it. Since iterators and references to objects are not invalidated, it is OK to access an element in the map via an iterator or a reference even while the map is modified - unless, of course, the element may be removed.

like image 196
Dietmar Kühl Avatar answered Oct 15 '25 01:10

Dietmar Kühl