1

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!

3
  • Why not just parallelize the the outer loop over t? If you're really creating a new matrix every time step then each thread will write to a private version of the matrix.
    – Z boson
    Feb 19, 2014 at 13:09
  • And what do you mean the code does not work? Do you get syntax errors?
    – Z boson
    Feb 19, 2014 at 13:14
  • I would use #pragma omp master instead of single. That way threads do not need to negotiate which one executes the code. Mar 11, 2014 at 19:31

2 Answers 2

1

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.

0

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
{

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.