C ++ 11 STL容器和线程安全 [英] C++11 STL containers and thread safety
问题描述
我无法找到关于此的任何最新信息。
Do C ++ 11版本的STL容器有一定程度的线程安全性? / p>
我预期他们不会,由于性能原因。但是,再次,这就是为什么我们有 vector :: operator []
和 vector :: at
。
由于现有的答案不覆盖它(只有一个注释),我只提到23.2.2 [container.requirements .dataraces]的当前 C ++标准规范,其中说:
向量除了 之外的不同元素中包含的对象的内容是相同的序列时,需要使用
实现来避免数据竞争同时修改。
ie它可以安全地访问同一个容器的不同元素,例如你可以有一个全局 std :: vector< std :: future< int>>
有十个线程,每个写入向量的不同元素。
除此之外,相同的规则适用于容器和其余的标准库(见17.6 .5.9 [res.on.data.races]),因为 Mr.C64的回答说,另外[container.requirements .dataraces]列出了一些可以安全调用的非const成员函数,因为它们只返回对元素的非const引用,它们实际上不修改任何东西(通常任何非const成员函数必须被认为是修改。 )
I have trouble finding any up-to-date information on this.
Do C++11 versions of STL containers have some level of thread safety guaranteed?
I do expect that they don't, due to performance reasons. But than again, that's why we have both vector::operator []
and vector::at
.
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:
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.
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.
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容器和线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!