問題描述
以下代碼只是并行化第一個(外部)循環,還是并行化整個嵌套循環?
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 如何處理嵌套循環?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!