C++11 says the following about the thread safetly of containers in the standard library:
23.2.2 Container data races [container.requirements.dataraces]
For purposes of avoiding data races (17.6.5.9), implementations shall
consider the following functions to be const: begin
, end
,
rbegin
, rend
, front
, back
, data
, find
, lower_bound
,
upper_bound
, equal_range
, at
and, except in associative or
unordered associative containers, operator[]
.
Notwithstanding (17.6.5.9), implementations are required to avoid data
races when the contents of the contained object in different elements
in the same sequence, excepting vector<bool>
, are modified
concurrently.
So, basically reading from a container from multiple threads is fine, and modifying elements that are already in the container is fine (as long as they are different elements).
So, neither of your two more specific questions are thread safe for std::vector
:
1) Two threads inserting into the vector is modifying the vector itself - not existing separate elements.
2) One thread erasing and other walking to access the same element is not safe because erasing an element from the vector isn't an operation that is promised to be thread safe (or "free from data races", as the standard puts it).
To perform those operations safely will require that the program impose some external synchronization itself.
std::vector
is one) is read. As soon as you introduce a potential for concurrent write-operation on the same object within , the wheels begin to fall off, and unless the objects themselves support atomic updates in that scenario, the wheels have left the vehicle. And if the container itself is to undergo any potentially layout-altering mechanics, the wheels are already a quarter-mile behind you in the ditch. – Klaraklarika