问题
What does it mean to make a dynamic array thread-safe and concurrent?
Say, for example, std::vector
.
- Two threads may want to insert at the same position. No synchronization needed as it will be done as per thread scheduling.
- One thread erasing and another going to access the same element? This is not a data structure issue I believe, it is a usage problem.
So is there anything that needs to be done over std::vector
to make it thread-safe and concurrent or is it thread-safe and concurrent by default?
回答1:
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.
回答2:
The only concurrent operations on a single object in the standard library that are safe by default are
- Only accessing const
-member functions
- All accesses to synchronization primitives (like mutex lock and unlock or atomic operations)
Everything else has to be externally synchronized. In particular, the standard library doesn't have any thread safe containers yet (as of c++14)
So the answer to both of your examples is no, they both require a form of external synchronization.
What you can do of course is modifying the value of two different elements in the container.
来源:https://stackoverflow.com/questions/31131743/is-stdvector-thread-safe-and-concurrent-by-default-why-or-why-not