Skip to content

Using OpenMP in c++ class

An answer to this question on Stack Overflow.

Question

I'm new to OpenMP. I'm trying to use OpenMP in my c++ code. The code is too complicated so I simplify the question as follow:

class CTet
{
    ...
    void cal_Mn(...);
}
int i, num_tet_phys;
vector<CTet> tet_phys;
num_tet_phys = ...;
tet_phys.resize(num_tet_phys);
#pragma omp parallel private(i)
for (i = 0; i < num_tet_phys; i++)
    tet_phys[i].cal_Mn(...);

I hope that the for loop can run in parallel but it seems that all threads run the whole loop independently. The calculation is repeated by every threads. What's problem in my code? How to fix it? Thank you!

Jun

Answer

Try

#pragma omp parallel for private(i)
for (i = 0; i < num_tet_phys; i++)
  tet_phys[i].cal_Mn(...);

Note the use of parallel for.

and compile with the -fopenmp flag.

The #pragma omp parallel creates a team of threads, all of which execute the next statement (in your case, the entire for loop). After the statement, the threads join back into one.

The #pragma omp parallel for creates a team of threads, which divide the work of the for loop between them.