Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 646
anon Avatar asked Jan 31 '10 04:01

anon


People also ask

Are std::map thread-safe?

It isn't thread safe, insert from two threads and you can end up in an inconstant state.

Is std :: function thread-safe?

Calling the function it points to is as thread-safe as the code being called; no more, and no less. And even if you make a copy in the first case, you still need protection, so long as there is a potential writer somewhere in the mix.

Is reading from a map thread-safe C++?

The map you use is immutable de facto so any find will actually do a find in a map which does not change. 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.

Is std :: list size () thread-safe?

No, they're not thread-safe.


1 Answers

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.

like image 164
dalle Avatar answered Sep 22 '22 05:09

dalle