在 openmp 中迭代 std 容器
我正在尝试使用 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
迭代到 s.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 以来,并且仅适用于随机访问迭代器(例如 vector
和 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);
}
}
}
开销相当大,因为每个线程遍历整个序列(但只对其中的一些执行operate
).您使用 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 对 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.
相关文章