问题描述
根据此主题,,其中的数据结构是在并行for循环中的 shared std :: vector?主要方面是速度,向量可能需要在循环期间调整大小。
Based on this thread, OpenMP and STL vector, which data structures are good alternatives for a shared std::vector in a parallel for loop? The main aspect is speed, and the vector might require resizing during the loop.
推荐答案
在多个线程写入单个容器的情况下,STL向量容器不是线程安全的。这只是真的,如正确地说,如果你调用的方法,可以导致重新分配的底层数组 std :: vector
成立。 push_back()
, pop_back()
和 insert()
是这些危险方法的示例。
The question you link was talking about the fact that "that STL vector container is not thread-safe in the situation where multiple threads write to a single container" . This is only true, as stated correctly there, if you call methods that can cause reallocation of the underlying array that std::vector
holds. push_back()
, pop_back()
and insert()
are examples of these dangerous methods.
如果您需要线程安全重新分配,则为您提供。你不应该在单线程程序中使用tbb :: concurrent_vector,因为访问随机元素所花费的时间比std :: vector需要做的时间更长(这是O(1))。然而,并发向量调用 push_back()
, pop_back()
, insert
If you need thread safe reallocation, then the library intel thread building block offers you concurrent vector containers . You should not use tbb::concurrent_vector in single thread programs because the time it takes to access random elements is higher than the time std::vector takes to do the same (which is O(1)). However, concurrent vector calls push_back()
, pop_back()
, insert()
in a thread safe way, even when reallocation happens.
编辑1:介绍了使用tbb :: concurrent_vector
EDIT 1: The slides 46 and 47 of the following Intel presentation give an illustrative example of concurrent reallocation using tbb::concurrent_vector
编辑2:顺便说一下,如果你开始使用英特尔Tread Building Block(它是开源的,它适用于大多数编译器,它是更好的集成C ++ / C ++ 11功能比openmp),那么你不需要使用openmp创建一个parallel_for,是一个很好的例子,parallel_for使用tbb 。
EDIT 2: By the way, if you start using Intel Tread Building Block (it is open source, it works with most compilers and it is much better integrated with C++/C++11 features than openmp), then you don't need to use openmp to create a parallel_for, Here is a nice example of parallel_for using tbb.
这篇关于C ++ OpenMP Parallel For Loop - std :: vector的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!