C++11 STL containers and thread safety(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.)
这篇关于C++11 STL 容器和线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++11 STL 容器和线程安全


基础教程推荐
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 设计字符串本地化的最佳方法 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01