在openmp中通过std容器迭代 [英] Iteration through std containers in openmp
问题描述
我试图使用openmp通过std :: set的多线程一个循环。当我写下面的代码 -
I'm trying to use openmp to multithread a loop through std::set. When I write the following code -
#pragma omp parallel for
for (std::set<A>::const_iterator i = s.begin(); i != s.end(); ++i) {
const A a = *i;
operate(a);
}
我收到此错误:
error: invalid type for iteration variable 'i'
error: invalid controlling predicate
error: invalid increment expression.
是否有另一种正确的方法使用openmp迭代std容器?
我知道我可以使用 int i
并从 0
到 .size()
和循环体中的迭代器或 operator []
,但这看起来不那么干净。
Is there an another, correct way to iterate through std containers using openmp?
I know I can use int i
and iterate from 0
to s.size()
and an iterator or operator[]
in the loop body, but this looks much less clean.
推荐答案
stl迭代器的循环并行化仅适用于OpenMP 3.0,并且只适用于随机访问迭代器(例如向量
和 deque
)。你应该能够这样做:
Loop parallelization for stl iterators only works since OpenMP 3.0, and only for random access iterators (e.g. vector
and deque
). You should be able to do something like this:
#pragma omp parallel {
for (std::set<A>::const_iterator i = s.begin(); i != s.end(); ++i) {
#pragma omp single nowait {
operate(*i);
}
}
}
开销相当大,每个线程遍历整个序列(但是只对其中一些执行 operations
)。您的方法使用 int i
更有效率。
Overhead is quite big though because each thread iterates over the whole sequence (but only executes operate
on some of it). Your method using an int i
is more efficient.
另一个替代方法是查看GCC的并行实现< a href =http://gcc.gnu.org/onlinedocs/libstdc++/manual/parallel_mode.html =nofollow> std :: for_each
。查看我的评论。
As an alternative take a look at GCC's parallel implementation of std::for_each
. See my comment.
编辑:STL Parallism TS ,很可能是C ++ 17的一部分,可能是将来对标准容器进行迭代的一个很好的选择。
EDIT: The STL Parallism TS, which will most likely be part of C++17, might be a good option in the future for iterating over standard containers.
这篇关于在openmp中通过std容器迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!