是std :: map和std :: vector线程安全吗? [英] Are std::map and std::vector thread safe?
问题描述
我正在开发一个多线程应用程序,每个线程将从一组映射和向量中读取(将不会修改结构)。任何人都可以告诉,因为线程只是从这些结构读取,有必要在这些结构被读取的代码块周围实现一个可共享互斥体?
I am developing a multi threaded application, each thread will read (there will be no modifying of structures) from a group of maps and vectors. Can anyone please advise, since the threads are only reading from these structures would it be necessary to implement a sharable mutex around the code blocks where these structures are being read?
推荐答案
在只读映射/向量的情况下,不需要使用互斥体。
这已经回答了向量和地图
虽然C ++ 03 doesn
In case of read only map/vector there is no need to use mutexes.
This was already answered for both vector and map
While C++03 doesn't mention threads, C++11 has clause covering you question.
1为了避免数据竞争(17.6.5.9),实现应考虑以下函数为
const:begin,end,rbegin,rend,前缀,后面,数据,查找,下限,上限,等于,在
和除了在关联或无序的关联容器中,operator []。
2尽管(17.6.5.9)当包含
对象的同一序列中不同元素中的内容除了向量< bool>
时,需要避免数据竞争。
3 [注意:对于大小大于1的向量< int>
x,x [1] = 5和* x.begin()= 10可以在没有数据竞争的情况下同时执行
,但是x [0] = 5和* x.begin()= 10同时执行可能导致
a数据竞争。作为一般规则的例外, bool> y,y [0] = true可能与y [1]竞争
= true。 -end note]
1 For purposes of avoiding data races (17.6.5.9), implementations shall consider the following functions to be const: begin, end, rbegin, rend, front, back, data, find, lower_bound, upper_bound, equal_range, at and, except in associative or unordered associative containers, operator[].
2 Notwithstanding (17.6.5.9), implementations are required to avoid data races when the contents of the contained object in different elements in the same sequence, exceptingvector<bool>
, are modified concurrently.
3 [ Note: For avector<int>
x with a size greater than one, x[1] = 5 and *x.begin() = 10 can be executed concurrently without a data race, but x[0] = 5 and *x.begin() = 10 executed concurrently may result in a data race. As an exception to the general rule, for a vector < bool > y, y[0] = true may race with y[1] = true. —end note ]
因此,在C ++ 11中,不仅允许读取对象,对象(但不是容器!), bool>
Thus in C++11 it is allowed not only to read objects , but also allow concurrent modification of its different objects(but not container!), with exception for vector < bool >
这篇关于是std :: map和std :: vector线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!