safe and concurrent by default? Why or why not?
What does it mean to make a dynamic array thread-safe and concurrent? Say, for example, std::vector
.
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?
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.
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.
链接地址: http://www.djcxy.com/p/13288.html上一篇: 什么是遗留集合`Stack`和`Properties`的替代品?
下一篇: 安全和默认并发? 为什么或者为什么不?