Can multiple threads access a vector at different places?

Since C++11:

Different elements in the same container can be modified concurrently by different threads, except for the elements of std::vector< bool> (for example, a vector of std::future objects can be receiving values from multiple threads).

cppreference discusses the thread safety of containers here in good detail. Link was found in a Quora post.


Yes, for most implementations of vector, this should be ok to do. That said, this will have very poor performance on most systems, unless you have a very large number of elements and you are accessing elements that are far apart from each other so that they don't live on the same cache line... otherwise, on many systems, the two threads will invalidate each other's caches back-and-forth (if you are frequently reading/writing to those elements), leading to lots of cache misses in both threads.


The fact that "vector is not thread-safe" doesn't mean anything. There's no problem with doing this.

Also you don't have to allocate your vector on heap (as one of the answers suggested). You just have to ensure that the lifetime of your vector covers the lifetime of your threads (more precisely - where those threads access the vector).

And, of course, since you want your both threads to work on the same vector - they must receive it from somewhere by pointer/reference rather than by value.

There's also absolutely no problem to access the same element of the array from within different threads. You should know however that your thread is not the only one that accesses it, and treat it respectively.

In simple words - there's no problem to access an array from within different threads. Accessing the same element from different thread is like accessing a single variable from different thread - same precautions/consequences.

The only situation you have to worry about is when new elements are added, which is impossible in your case.


Yes, this should be fine. As long as you can guarantee that different threads won't modify the same memory location, there's no problem.