6

I am developing a multi threaded application, each thread will read (there will be no modifying of structures) from a group of maps and vectors. Can anyone please advise, since the threads are only reading from these structures would it be necessary to implement a sharable mutex around the code blocks where these structures are being read?

godzilla
  • 3,005
  • 7
  • 44
  • 60
  • Related question and answers here on SO: [C++11 STL containers and thread safety](http://stackoverflow.com/questions/12931787/c11-stl-containers-and-thread-safety). – Mr.C64 Apr 21 '13 at 15:34

1 Answers1

15

In case of read only map/vector there is no need to use mutexes. This was already answered for both vector and map
While C++03 doesn't mention threads, C++11 has clause covering you question.

23.2.2 Container data races [container.requirements.dataraces]

1 For purposes of avoiding data races (17.6.5.9), implementations shall consider the following functions to be const: begin, end, rbegin, rend, front, back, data, find, lower_bound, upper_bound, equal_range, at and, except in associative or unordered associative containers, operator[].
2 Notwithstanding (17.6.5.9), implementations are required to avoid data races when the contents of the contained object in different elements in the same sequence, excepting vector<bool>, are modified concurrently.
3 [ Note: For a vector<int> x with a size greater than one, x[1] = 5 and *x.begin() = 10 can be executed concurrently without a data race, but x[0] = 5 and *x.begin() = 10 executed concurrently may result in a data race. As an exception to the general rule, for a vector < bool > y, y[0] = true may race with y[1] = true. —end note ]

Thus in C++11 it is allowed not only to read objects , but also allow concurrent modification of its different objects(but not container!), with exception for vector < bool >

Community
  • 1
  • 1
alexrider
  • 4,449
  • 1
  • 17
  • 27
  • and what about other class members? When would it be necessary to use a shared mutex? – godzilla Apr 21 '13 at 11:14
  • @godzilla once container is going to be modified, you will need to use mutex on both read and write. In case of immutable read only container it can be accessed from different threads concurrently. – alexrider Apr 21 '13 at 11:17
  • Actually I think the standard doesn’t give any guarantees whatsoever. It certainly doesn’t for C++03, maybe it does for C++11. But no sane implementation would be thread unsafe in this scenario. – Konrad Rudolph Apr 21 '13 at 11:18
  • @KonradRudolph C++03 doesn't mention threads indeed, thru there is `23.2.2 Container data races` clause in C++ 11 – alexrider Apr 21 '13 at 11:25