在 openmp 中迭代 std 容器

2024-05-11C/C++开发问题
13

本文介绍了在 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 以来,并且仅适用于随机访问迭代器(例如 vectordeque).你应该能够做这样的事情:

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.

这篇关于在 openmp 中迭代 std 容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6