【问题标题】:Parallelizing an inner loop with OpenMP使用 OpenMP 并行化内部循环
【发布时间】:2015-04-13 16:30:16
【问题描述】:

假设我们有两个嵌套循环。内循环应该是并行的,但是外循环需要顺序执行。然后下面的代码做我们想做的事:

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

我该如何解决这个问题?

  1. 每个线程应该只请求一次本地对象。

  2. 内部循环应该在所有线程之间并行化。

  3. 外循环的迭代应该一个接一个地执行。

我的想法如下,但它真的是我想要的吗?

#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
    }
  }
}

【问题讨论】:

  • @HighPerformanceMark,除了错别字,我认为 OPs 问题很有趣,这在最近的 OpenMP 问题中很少见。您在我的解决方案中使用threadprivate 是否有任何 cmets?我是不是弄错了(我现在几乎只用 C,而且我的 C++ 超级生锈)?
  • 你的方法很好。你能告诉我为什么你需要一个初始化为线程号的线程本地对象吗?

标签: c++ multithreading openmp


【解决方案1】:

当您可以简单地使用pool of objects 时,我真的不明白为什么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
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    相关资源
    最近更新 更多