Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pragma omp parallel for vs. pragma omp parallel

Tags:

c++

openmp

In C++ with openMP, is there any difference between

#pragma omp parallel for
for(int i=0; i<N; i++) {
   ...
}

and

#pragma omp parallel
for(int i=0; i<N; i++) {
   ...
}

?

Thanks!

like image 942
Francisco J. R. Ruiz Avatar asked Jun 28 '16 15:06

Francisco J. R. Ruiz


People also ask

What is the difference between OMP for and OMP parallel for?

#pragma omp parallel spawns a group of threads, while #pragma omp for divides loop iterations between the spawned threads.

What is pragma OMP parallel for?

Purpose. The omp parallel directive explicitly instructs the compiler to parallelize the chosen block of code.

Is OpenMP parallel or concurrent?

OpenMP will: Allow a programmer to separate a program into serial regions and parallel regions, rather than T concurrently-executing threads.


1 Answers

#pragma omp parallel
for(int i=0; i<N; i++) {
   ...
}

This code creates a parallel region, and each individual thread executes what is in your loop. In other words, you do the complete loop N times, instead of N threads splitting up the loop and completing all iterations just once.

You can do:

#pragma omp parallel
{
    #pragma omp for
    for( int i=0; i < N; ++i )
    {
    }

    #pragma omp for
    for( int i=0; i < N; ++i )
    {
    }
}

This will create one parallel region (aka one fork/join, which is expensive and therefore you don't want to do it for every loop) and run multiple loops in parallel within that region. Just make sure if you already have a parallel region you use #pragma omp for as opposed to #pragma omp parrallel for as the latter will mean that each of your N threads spawns N more threads to do the loop.

like image 55
RyanP Avatar answered Sep 24 '22 04:09

RyanP