C++ STL vector iterator vs indexes access and thread safety
c++, multithreading, stl, thread-safety
Solution
OP "Does my choice of accessing the container through indexes(Approach 1) in place of iterators(Approach 2) make it thread safe?"
No, neither approach is thread safe once you start writing to your data structure.
Therefore you will need to serialize access to your data structure.
To save you a lot of time and frustration there a lot of ready-rolled solutions e.g.
Intel Threading Building Blocks (TBB) which comes with thread safe containers such as `concurrent_vector`.
http://threadingbuildingblocks.org/
A concurrent_vector is a container with the following features:
- Random access by index. The index of the first element is zero.
- Multiple threads can grow the container and append new elements concurrently.
- Growing the container does not invalidate existing iterators or indices.*
OP "What about performance?"
Not knowable. Different performance on different systems with different compilers but not known to be large enough to influence your choices.
Problem
I am iterating over an STL vector and reading values from it. There is another thread which can make changes to this vector. Now, if the other thread inserts or removes and element from the vector, it invalidates the iterator. There is no use of locks involved. Does my choice of accessing the container through indexes(Approach 1) in place of iterators(Approach 2) make it thread safe? What about performance? ``` struct A{int i; int j;}; ``` Approach 1: ``` size_t s = v.size();//v contains pointers to objects of type A for(size_t i = 0; i < s; ++i) { A* ptr = v[i]; ptr->i++; } ``` Approach 2: ``` std::vector<A*>::iterator begin = v.begin(); std::vector<A*>::iterator end = v.end(); for(std::vector<A*>::iterator it = begin; it != end; ++it) { A* ptr = *it; ptr->i++: } ```