我很难找到任何关于此的最新信息。
C++11 版本的 STL 容器是否保证了一定程度的线程安全?
由于性能原因,我确实希望他们不会这样做。但是话又说回来,这就是为什么我们都有 std::vector::operator[]
和 std::vector::at
.
最佳答案
由于现有答案没有涵盖它(只有评论),我只提当前 C++ standard specification 的 23.2.2 [container.requirements.dataraces]其中说:
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<int>>
十个元素,有十个线程,每个线程写入 vector 的不同元素。
除此之外,与标准库的其余部分相同的规则适用于容器(参见 17.6.5.9 [res.on.data.races]),如 Mr.C64's answer说,另外 [container.requirements.dataraces] 列出了一些可以安全调用的容器的非常量成员函数,因为它们只返回对元素的非常量引用,它们实际上并没有修改任何东西(通常是任何非常量成员函数必须被视为修改。)
关于C++11 STL 容器和线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12931787/