問題描述
以下代碼只是并行化第一個(gè)(外部)循環(huán),還是并行化整個(gè)嵌套循環(huán)?
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)//
}
}
我只想確定上面的代碼是否會(huì)并行化整個(gè)嵌套的 for 循環(huán)(因此一個(gè)線程直接與 task(i,j) 相關(guān)),或者它只并行化外部 for 循環(huán)(從而確保,對(duì)于每個(gè)循環(huán)索引為 i 的并行線程,其內(nèi)部循環(huán)將在單個(gè)線程中依次完成,這非常重要).
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).
推薦答案
您編寫的行將僅并行化外循環(huán).要并行化兩者,您需要添加一個(gè) 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 規(guī)范(第 2.5.1 節(jié))以了解更多詳細(xì)信息.
You may want to check OpenMP 3.1 specifications (sec 2.5.1) for more details.
這篇關(guān)于OpenMP 如何處理嵌套循環(huán)?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!