C++11 STL 容器和线程安全

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Returning a pointer of a local variable C++(返回局部变量 C++ 的指针)
Inline function linkage(内联函数联动)
Which is more efficient: Return a value vs. Pass by reference?(哪个更有效:返回值与通过引用传递?)
Why is std::function not equality comparable?(为什么 std::function 不具有可比性?)
C++ overload resolution(C++ 重载解析)
When to Overload the Comma Operator?(什么时候重载逗号运算符?)