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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…