Openmp: nested loops and allocation

I'd like to parallelize a for loop within another for loop. I can simply use the instruction "#pragma omp parallel for" directly in the inner loop, but I fear that creating a new set of threads each time is not the oprimal thing to do. In the outer loop (before the inner one) there is the allocation and some other instructions to be done by a single thread (I allocate a matrix to be worked sharely in the inner loop, so every thread should have access to it). I tried to do something like this:

     #pragma omp parallel
         {
        for (auto t=1;t<=time_step;++t){
        #pragma omp single {
        Matrix<unsigned int> newField(rows,cols);
        //some instructions
         }
        unsigned int j;
        #pragma omp  for
        for (unsigned int i = 2;i<=rows-1;++i){

            for ( j = 1;j<=cols;++j){
                           //Work on NewField (i,j)
            }
        }
        #pragma omp single {
           //Instruction
          }
        }
    }

This code doesn't work. Is this way (if I make it work) more efficient than creating the threads every time? What I am doing wrong?

Thank you!


Many implementations of OpenMP are keeping pool of threads instead of creating them before every parallel region.

So you can just go with

for (auto t=1;t<=time_step;++t){
    Matrix<unsigned int> newField(rows,cols);
    //some instructions
    unsigned int j;
    #pragma omp parallel for
    for (unsigned int i = 2;i<=rows-1;++i){
        for ( j = 1;j<=cols;++j){
            //Work on NewField (i,j)
        }
    }
    //Instruction
}

and it even could be faster because of absent single directives.


The way you have your code written now is going to cause syntax errors. When you use OpenMP directives such as single or critical the braces must be on a new line.

So instead of this

#pragma omp single {

}

You need to do this

#pragma omp single
{

}
链接地址: http://www.djcxy.com/p/79236.html

上一篇: C ++

下一篇: Openmp:嵌套循环和分配