What operations are thread-safe on std::map?

anon picture anon · Jan 31, 2010 · Viewed 19.4k times · Source

Suppose I have:

stl::map<std::string, Foo> myMap;

is the following function thread safe?

myMap["xyz"] ?

I.e. I want to have this giant read-only map that is shared among many threads; but I don't know if even searching it is thread safe.


Everything is written to once first.

Then after that, multiple threads read from it.

I'm trying to avoid locks to make this as faast as possible. (yaya possible premature optimization I know)

Answer

dalle picture dalle · May 4, 2013

C++11 requires that all member functions declared as const are thread-safe for multiple readers.

Calling myMap["xyz"] is not thread-safe, as std::map::operator[] isn't declared as const. Calling myMap.at("xyz") is thread-safe though, as std::map::at is declared as const.