C++11 STL 容器和线程安全
我无法找到任何关于此的最新信息.
I have trouble finding any up-to-date information on this.
C++11 版本的 STL 容器是否有一定程度的线程安全保证?
Do C++11 versions of STL containers have some level of thread safety guaranteed?
由于性能原因,我确实希望它们不会.但话又说回来,这就是为什么我们有 std::vector::operator[]
和 std::vector::at
.
I do expect that they don't, due to performance reasons. But then again, that's why we have both std::vector::operator[]
and std::vector::at
.
推荐答案
由于现有的答案没有涵盖它(只有评论可以),我将仅提及 23.2.2 [container.requirements.dataraces]当前 C++ 标准规范 说:
Since the existing answers don't cover it (only a comment does), I'll just mention 23.2.2 [container.requirements.dataraces] of the current C++ standard specification which says:
当同时修改同一序列中不同元素中包含的对象的内容时(vector
除外),需要实现以避免数据竞争.
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.
即访问同一容器的不同元素是安全的,例如,您可以拥有一个包含十个元素的全局 std::vector<std::future
i.e. it's safe to access distinct elements of the same container, so for example you can have a global std::vector<std::future<int>>
of ten elements and have ten threads which each write to a different element of the vector.
除此之外,容器的规则与标准库的其余部分相同(参见 17.6.5.9 [res.on.data.races]),如 C64 先生的回答 说,另外 [container.requirements.dataraces] 列出了一些可以安全调用的容器的非常量成员函数,因为它们只返回非常量引用元素,它们实际上并没有修改任何东西(通常任何非常量成员函数都必须被视为修改.)
Apart from that, the same rules apply to containers as for the rest of the standard library (see 17.6.5.9 [res.on.data.races]), as Mr.C64's answer says, and additionally [container.requirements.dataraces] lists some non-const member functions of containers that can be called safely because they only return non-const references to elements, they don't actually modify anything (in general any non-const member function must be considered a modification.)
相关文章