Sunday, 14 July 2013

Nested Parallelism OpenMP example

Posted by Mahesh Doijade
nested parallelism openmp, openmp, openmp parallel

       Nested Parallelism was introduced in OpenMP since OpenMP 2.5. Nested Parallelism enables the programmer to create parallel region within a parallel region itself. So, each thread in the outer parallel region can spawn more number of threads when it encounters the another parallel region. Nested parallelism can be put into effect at runtime by setting various environment variables prior to execution of the program.  It can be used by either setting the environment variable OMP_NESTED as TRUE or the other way is to call the function omp_set_nested() and passing it parameter '1' to enable nested parallelism or '0' to disable nested parallelism. The nested parallelism with OpenMP basic example is given below, compile this code using g++ with -fopenmp flag

#include <iostream>
#include <stdio.h>
#include <omp.h>

using namespace std;

int main()
{
    int number;
    int i;
    omp_set_num_threads(4);
    omp_set_nested(1); // 1 - enables nested parallelism; 0 - disables nested parallelism.

    #pragma omp parallel // parallel region begins
    {       
        printf("outer parallel region Thread ID == %d\n", omp_get_thread_num());
        /*
            Code for work to be done by outer parallel region threads over here.
        */
        #pragma omp parallel num_threads(2) // nested parallel region
        {   
            /*
                Code for work to be done by inner parallel region threads over here.
            */       
            printf("inner parallel region thread id %d\n", omp_get_thread_num());
           
            #pragma omp for
            for(i=0;i<20;i++)
            {
                // Some independent iterative computation to be done.
            }
        }
    }
    return 0;
}

0 comments:

Post a Comment