开发者

Iteration through std containers in openmp

I'm trying to use openmp to multithread a loop through std::set. When I write the followin开发者_JS百科g code -

    #pragma omp parallel for
    for (std::set<A>::const_iterator i = s.begin(); i != s.end(); ++i) {
            const A a = *i;
            operate(a);
    }

I get this error:

error: invalid type for iteration variable 'i'
error: invalid controlling predicate
error: invalid increment expression.

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.


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);
      }
   }
}

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.

As an alternative take a look at GCC's parallel implementation of std::for_each. See my comment.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜