Is reference to object in std::map is thread safe?
std::map< std::string, Object > _objects;
map can be changed from many threads and this access is synchronized, but reference to value (Object &) accessable just from 1 instance and thread. is write operations with Object & is safe if another thread will add items to map? will it reallocate?
The C++11 standard guarantees that const
method access to containers is safe from different threads (ie, both use const
methods).
In addition, [container.requirements.dataraces] states
implementations are required to avoid data races when the contents of the contained object in different elements in the same sequence, excepting
vector<bool>
In other words, except for vector<bool>
modifying distinct contents is not a data race.
Now, if one thread invalidates an iterator used by another thread, clearly this is a data race (and results in undefined behavior). If one thread does non-const
access to a container, and another does const
access, that is a data race (and undefined behavior). (Note: a number of functions are "considered const
" for the purpose of multithreading, including begin
, end
and other functions (and methods) that are non-const
simply because they return non-const
iterators. []
is included in this set of pseudo-const
for thread safety reasons, except for map
and unordered_set
etc -- 23.2.2.1).
However, it appears that if you have a reference to an element within the container, and engage in operations that do not invalidate that reference in another thread, and never write to that element in another thread, you can safely read from that reference. Similarly, if other threads never even read from the element, then writing to that element shouldn't result in undefined behavior.
For standards references, 17.6.5.9.5 seems to guarantee that functions from the standard library won't run away and read/write elements needlessly.
So the short answer: you are safe, so long as the other thread doesn't directly mess with that particular entry in the map
.