0

I have a stl map with integer as key and a vector of class object as its value.

class foo {
    // provides wrapper around std::queue for thread safety
    private :
       std::queue<>
}

std::map<unsigned int, std::vector<foo *> > mymap;

foo class is just a thread safe wrapper around std::queue implementation. Now coming to the actual question - this map is used in a multi threaded scenario where each thread depending upon an arguments passed during creation accesses the corresponding vector.

So lets say i created 4 threads and passed 0,1,2,3 as argument so :

thread 0 - mymap[0];
thread 1 - mymap[1];
thread 2 - mymap[2];
thread 3 - mymap[3];
  1. Size of the map is fixed during creation and is not changed.

Do i need to make my map thread safe ?

  1. as the size of map is fixed so that there will be no re-ordering of the map .
  2. each thread changes only its corresponding vector as per its id.
Dexter
  • 1,299
  • 3
  • 20
  • 38
  • 1
    Reading from multiple thread is safe. Take a look at this - http://stackoverflow.com/questions/1846186/thread-safety-of-stdmap-for-read-only-operations – army007 Apr 02 '17 at 11:07
  • Im my case the vector size gets modified. Only the size of map remains consistent – Dexter Apr 02 '17 at 11:22
  • I am wondering if insert or delete some element in the vector is reflected in corresponding `mymap[]` vector after these threads are joined with `main()` thread. In any case, these vectors are not shared among threads. So it should be okay. – army007 Apr 02 '17 at 11:26
  • Why just not to switch to using `std::thread_local`. See here http://en.cppreference.com/w/cpp/keyword/thread_local. From your description it looks like this is what you need, in case you dont iterate the whole `map` to retrieve some data from various `vectors` – kreuzerkrieg Apr 02 '17 at 12:33

1 Answers1

0

No, you do not need to add extra synchronization to make this use of std::map thread-safe. You are only modifying the map nodes during initialization, and after that you are only reading the map. Concurrent reading of the map is no problem, because its structure does not change.

The fact that you are modifying the values in the map does not matter, because they don't contribute to the ordering and structure of the map.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436