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)
It isn't thread safe, insert from two threads and you can end up in an inconstant state.
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.
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.
No, they're not thread-safe.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With