c++:OpenMP 和非随机访问 STL 容器 - 一种可能的解决方法
c++: OpenMP and non-random-access STL containers - a possible workaround
所以在SO和一般的互联网上,关于如何使OpenMP易于使用的#pragma
指令与C++同样易于使用的STL容器配合使用,存在很多困惑和沮丧。
每个人都在谈论STL vector
的解决方法,但是非随机访问/双向容器,如map
,list
,set
等呢?
我遇到了这个问题,并设计了一个非常简单,明显的解决方法。 我在这里为STL map
提出它,但它显然是可以推广的。
序列号版本:
for (std::map<A,B>::iterator it = my_map.begin();
it != my_map.end();
++it)
{ /* do work with it */ }
我建议的解决方案是将 OpenMP 与 STL 一起使用map
:
//make an array of iterators.
int loop_length = my_map.size();
std::map<A,B>::iterator loop_array[ loop_length ];
std::map<A,B>::iterator allocate_it = my_map.begin();
for (int j=0; j<loop_length; ++j)
loop_array[j] = allocate_it++;
// now you can use OpenMP as usual:
#pragma omp parallel for
for (uint j=0; j<loop_length; ++j)
{ /* do work with loop_array[j] */ }
然而,我远非OpenMP的专家,所以我想知道我提出的解决方法是否有效和良好实践。
请假设程序员负责 for 循环中 STL 容器的线程安全处理。
最后,我提出的解决方案是否比以下通常提出的解决方案更有效(请参阅此 SO 问题的答案(,因为在我的解决方案中,每个线程都不会遍历整个容器?
#pragma omp parallel
{
for (std::map<A,B>::iterator it = my_map.begin();
it != my_map.end();
++it)
#pragma single nowait
{ /* do work */ }
}
OpenMP 提供了从版本 3.0 开始的task
结构,这对于与 STL 一起使用非常有用:
for (std::map<A,B>::iterator it = my_map.begin();
it != my_map.end();
++it)
{
#pragma omp task
{ /* do work with it */ }
}
当然,迭代之间的数据依赖关系不应该存在,这要起作用。
相关文章:
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 有没有一种方法可以在编译时获得作用域类名
- 有没有一种方法可以测量c++程序的运行时内存使用情况
- 有没有一种方法可以使用placement new将堆叠对象分配给分配的内存
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 在 c++ 中,有一种方法可以创建一个包含地图作为值的树状地图?
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 有没有一种方法可以捕获进程中的堆栈溢出?C++Linux
- 我想直接在结构中插入,但没有一种方法可以正确避免填充问题
- 类中一种方法的部分专用化
- 只需要知道我在c ++中打印模式的方式是否有效,或者有另一种方法可以有效地做到这一点
- 有没有一种方法可以忽略Qt c++中的文件名大小写敏感性?
- 有没有一种方法可以使用图形在C++中逐个字母地打印控制台中的文本
- 有没有一种方法可以将数据从javascript发送到exe文件
- 有没有一种方法可以从函数中返回一个新对象或对现有对象的引用
- 在C++中,有没有一种方法可以让我在不传递参数的情况下拥有一个函数
- 有没有一种方法可以使用SFINAE来检测一个类型是否实现了给定的抽象基类
- 有没有一种方法可以使用typedef中的参数名称
- C++中有没有一种方法可以通过指定列表中的每个成员变量来构造对象