将内部循环与OpenMP并行
Parallelizing an inner loop with OpenMP
假设我们有两个嵌套循环。内部循环应该是并行的,但外部循环需要按顺序执行。然后下面的代码做我们想要的:
for (int i = 0; i < N; ++i) {
#pragma omp parallel for schedule(static)
for (int j = first(i); j < last(i); ++j) {
// Do some work
}
}
现在假设每个线程都必须获得一些线程本地对象来执行内部循环中的工作,并且获得这些线程本地对象的成本很高。因此,我们不想做以下事情:
for (int i = 0; i < N; ++i) {
#pragma omp parallel for schedule(static)
for (int j = first(i); j < last(i); ++j) {
ThreadLocalObject &obj = GetTLO(omp_get_thread_num()); // Costly!
// Do some work with the help of obj
}
}
我该如何解决这个问题?
每个线程只应请求其本地对象一次。
内部循环应该在所有线程之间并行化。
外部循环的迭代应该一个接一个地执行。
我的想法如下,但它真的想要我想要吗?
#pragma omp parallel
{
ThreadLocalObject &obj = GetTLS(omp_get_thread_num());
for (int i = 0; i < N; ++i) {
#pragma omp for schedule(static)
for (int j = first(i); j < last(i); ++j) {
// Do some work with the help of obj
}
}
}
当您可以简单地使用对象池时,我真的不明白为什么threadprivate
的复杂性是必要的。基本想法应该沿着以下几条线:
#pragma omp parallel
{
// Will hold an handle to the object pool
auto pool = shared_ptr<ObjectPool>(nullptr);
#pragma omp single copyprivate(pool)
{
// A single thread creates a pool of num_threads objects
// Copyprivate broadcasts the handle
pool = create_object_pool(omp_get_num_threads());
}
for (int i = 0; i < N; ++i)
{
#pragma omp parallel for schedule(static)
for (int j = first(i); j < last(i); ++j)
{
// The object is not re-created, just a reference to it
// is returned from the pool
auto & r = pool.get( omp_get_thread_num() );
// Do work with r
}
}
}
相关文章:
- OpenMP:并行更新数组总是需要减少数组吗
- 如何使用OpenMP并行这两个循环
- 如何使用OpenMP并行化此矩阵时间矢量运算
- 两个连续的 OpenMP 并行区域会相互减慢速度
- 如何使用 OpenMP 并行化最近邻搜索
- OpenMP并行发送哪些元素
- 对于openMP来说,有什么建议可以将以下代码与openMP并行
- 是否可以使用OpenMP并行化一个列表,该列表可以在每次迭代中添加新元素
- std::lock_guard 在 OpenMP 并行中
- 使用与 openmp C++并行的循环计算矩阵中每一行的最小值
- 嵌套循环 OpenMP 并行化、私有索引还是公共索引?
- C++ openmp 并行计算计算错误的结果
- 在 C++ 中使用 OpenMP 并行化两个 for 循环不会提供更好的性能
- 我可以将映射迭代器与 OpenMP 并行使用吗?
- OpenMP C++:并行化 for 循环的负载不平衡
- Qimage setPixel with openmp 并行 for 不起作用
- 如何加快有序子句的 openmp 并行速度?
- 跨越多个函数/对象的OpenMP并行区域
- 使用 OpenMP 并行执行比串行执行 c++ 花费更长的时间,我计算执行时间是否正确?
- 尝试与 OpenMP 并行处理链表数据