OpenMP如何处理嵌套循环? [英] How does OpenMP handle nested loops?

查看:1299
本文介绍了OpenMP如何处理嵌套循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码只是并行化第一个(外部)循环,还是并行化整个嵌套循环?

Does the following code just parallelize the first (outer) loops, or it parallelize the entire nested loops?

    #pragma omp parallel for
    for (int i=0;i<N;i++)
    { 
      for (int j=0;j<M;j++)
      {
       //do task(i,j)//
      }
    }

我只想确保上面的代码是否会并行化整个嵌套的for循环(因此,一个线程直接与task(i,j)相关),或者仅并行化外部的for循环(从而确保,对于每个具有循环索引i的并行线程,其内部循环将在单个线程中按顺序完成(这非常重要).

I just want to make sure if the above code will parallelize the entire nested for-loops (thus one thread directly related task(i,j)), or it only parallelizes the outer for-loop (thus it ensures that, for each parrallel thread with loop index i, its inner loop will be done sequentially in a single thread, which is very import).

推荐答案

您编写的行将仅并行化外循环.要同时使两者并行化,您需要添加一个collapse子句:

The lines you have written will parallelize only the outer loop. To parallelize both you need to add a collapse clause:

#pragma omp parallel for collapse(2)
    for (int i=0;i<N;i++)
    { 
      for (int j=0;j<M;j++)
      {
       //do task(i,j)//
      }
    }

您可能想查看 OpenMP 3.1 规范(第2.5.1节)以了解更多详细信息

You may want to check OpenMP 3.1 specifications (sec 2.5.1) for more details.

这篇关于OpenMP如何处理嵌套循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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