Re: STL container read thread-safety.
On Apr 4, 8:26 pm, "jason.cipri...@gmail.com"
<jason.cipri...@gmail.com> wrote:
I know that the overall thread safety of STL containers is not
guaranteed. However, if I have an std::vector<int> or an
std::list<int>, and multiple threads are reading them but nothing is
writing them, do I still need to synchronize access to them? By
"reading" I mean iterating through with const_iterators, and also
copying them to other containers with the assignment operator.
For the copy (using assignment operator), the contention resource (if
it is being shared across threads) would become the conatiner to which
you are copying from the original list/vector/any other container. So,
you won't need synchronization for the original object but will need
it for the object it is being copied to.
What I mean is, am I guaranteed that, say, I don't know, obtaining a
const_iterator via std::list<int>::begin() isn't doing any internal
housekeeping or anything that would potentially make it not thread-
safe?
What about set and map?
The answer can probably be generalized across STL containers (depends
on STL implementation docs/guarantees as well). A usual mistake could
be modifying std::map with operator[]. It can be considered a bug in a
non-multithreaded app as well and might be a bit tough to catch in a
bigger codebase. So, that would be one point where I would be
cautious. Moreover, if there is a parallelized code section,
maintaining const-ness for the object that is just being read can be
useful to catch such errors. Just a thought.