How to parallel for loop inside single region in openMP?

对着背影说爱祢 提交于 2020-01-13 19:05:09

问题


I have a recursive program which I want to speed up using openMP. The structure is like below.

I am not familiar with omp task and just learnt something from here. It seems that I have to wrap buildTree in a omp single region.

However, I also want to parallelize the for loop inside buildTree, how can I achieve that?

int main()
{
    #pragma omp parallel 
    {
        #pragma omp single nowait
        buildTree();
    }
}
void buildTree
{
    if(endRecursion)
        return;
    for(int i = 0; i < problemSize; i++)
    {
        // I want to parallelize these code using omp for
    }

    if(problemSizeIsSmall)
    {
        buildTree(subProblemSize); // left subtree
        buildTree(subProblemSize); // right subtree
    }
    else
    {
        #pragma omp task
        {
            buildTree(subProblemSize); // left subtree
        }
        #pragma omp task
        {
            buildTree(subProblemSize); // right subtree
        }
    }
}

回答1:


I think you can use nested parallelism in your problem. Your code would look like this way in your main():

#pragma omp parallel for num_threads(2)
buildTree();

and in buildTree() :

omp_set_num_threads(4); // 4 or whatever number of threads you want
#pragma omp parallel for 
for(int i = 0; i < problemSize; i++)

Check the section 4.3 Example 4–2 Calls to OpenMP Routines Within Parallel Regions of my first link for more details



来源:https://stackoverflow.com/questions/30294883/how-to-parallel-for-loop-inside-single-region-in-openmp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!