使用循环在OpenMP中并行部分 [英] Parallel sections in OpenMP using a loop

查看:126
本文介绍了使用循环在OpenMP中并行部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否存在使用for循环在OpenMp中创建并行段的技术.

I wonder if there is any technique to create parallel sections in OpenMp using a for-loop.

例如,我不想创建n个不同的#pragma omp节,而是想使用n个迭代的 for循环来创建它们,并为每个节更改一些参数.

For example, instead of creating n different #pragma omp sections, I want to create them using an n-iteration for-loop with some changing parameters for each section.

#pragma omp parallel sections
{
   #pragma omp section
   {
      /* Executes in thread 1 */
   } 
   #pragma omp section
   {
      /* Executes in thread 2 */
   } 
   #pragma omp section
   {
      /* Executes in thread n */
   } 
}

推荐答案

具有显式OpenMP任务:

With explicit OpenMP tasks:

#pragma omp parallel
{
   // Let only one thread create all tasks
   #pragma omp single nowait
   {
       for (int i = 0; i < num_tasks; i++)
          #pragma omp task
          {
              // Code for task with parameters, based on i
          }
   }
   // Let the threads process all tasks
   #pragma omp taskwait

   // Further parallel processing ...
}

OpenMP task指令后面的代码块是显式任务.显式任务排队等待稍后执行. taskwait指令的作用类似于barrier,但用于任务.另请参阅此答案(类似问题).

The code block that follows the OpenMP task directive is an explicit task. Explicit tasks are queued an executed later. The taskwait directive acts similar to barrier, but for tasks. Also see this answer to a similar question.

任务可以递归创建其他任务.因此,可以使用显式任务来处理图形和树.但是要当心开销-它比大多数其他构造的开销大,并且与schedule(dynamic)循环产生的开销非常相似.另外,默认情况下,在任务内部引用的来自外部作用域的变量也是firstprivate.

Tasks can create other tasks recursively. So explicit tasking can be used to process graphs and trees. But beware of the overhead - it is bigger than the overhead from most other constructs and is quite similar to the one that comes from loops with schedule(dynamic). Also the variables from the outer scope, referenced inside the task are by default firstprivate.

请注意,显式任务是功能,它是OpenMP 3.0中添加的功能.符合早期OpenMP版本的编译器可能不支持task指令.几乎所有现代编译器都支持OpenMP 3.0或更高版本,但Microsoft Visual C ++例外,后者仅支持OpenMP 2.0(即使在VS2012中也是如此).

Note that explicit tasks are feature, that was added in OpenMP 3.0. Compilers that conform to earlier OpenMP versions might not support the task directive. Almost all modern compilers do support OpenMP 3.0 or later with the notable exception of Microsoft Visual C++, which only supports OpenMP 2.0 (even in VS2012).

这篇关于使用循环在OpenMP中并行部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆