問題描述
我無法找到任何關(guān)于此的最新信息.
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?
由于性能原因,我確實(shí)希望它們不會.但話又說回來,這就是為什么我們有 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
.
推薦答案
由于現(xiàn)有的答案沒有涵蓋它(只有評論可以),我將僅提及 23.2.2 [container.requirements.dataraces]當(dāng)前 C++ 標(biāo)準(zhǔn)規(guī)范 說:
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:
當(dāng)同時修改同一序列中不同元素中包含的對象的內(nèi)容時(vector
除外),需要實(shí)現(xiàn)以避免數(shù)據(jù)競爭.
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.
除此之外,容器的規(guī)則與標(biāo)準(zhǔn)庫的其余部分相同(參見 17.6.5.9 [res.on.data.races]),如 C64 先生的回答 說,另外 [container.requirements.dataraces] 列出了一些可以安全調(diào)用的容器的非常量成員函數(shù),因?yàn)樗鼈冎环祷胤浅A恳迷?,它們?shí)際上并沒有修改任何東西(通常任何非常量成員函數(shù)都必須被視為修改.)
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.)
這篇關(guān)于C++11 STL 容器和線程安全的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!