Thread safety of std::map for read-only operations

This will work from multiple threads as long as your map remains the same. The map you use is immutable de facto so any find will actually do a find in a map which does not change.

Here is a relevant link: http://www.sgi.com/tech/stl/thread_safety.html

The SGI implementation of STL is thread-safe only in the sense that simultaneous accesses to distinct containers are safe, and simultaneous read accesses to to shared containers are safe. If multiple threads access a single container, and at least one thread may potentially write, then the user is responsible for ensuring mutual exclusion between the threads during the container accesses.

You fall into he "simultaneous read accesses to shared containers" category.

Note: this is true for the SGI implementation. You need to check if you use another implementation. Of the two implementations which seem widely used as an alternative, STLPort has built-in thread safety as I know. I don't know about the Apache implementation though.


It should be fine. You can use const references to it if you want to document/enforce read-only behaviour.

Note that correctness isn't guaranteed (in principle the map could choose to rebalance itself on a call to find), even if you do use const methods only (a really perverse implementation could declare the tree mutable). However, this seems pretty unlikely in practise.


Yes it is.

See related post with same question about std::set:

Is the C++ std::set thread-safe?