Friday 15 January 2016

OpenMP Parallel Sections Example

                In this video, we will see OpenMP Sections | OpenMP Section Example | OpenMP Parallel Sections.
                In OpenMP, we can allocate different work to different threads by using sections. We have to use " #pragma omp parallel sections " for the same purpose.
                I have provided simple example, which creates three threads. Each thread does the distinct job. First thread is printing 'X', second thread 'Y' and third thread 'Z'. I am also printing thread ids, so that you can easily understand, threads are different and doing independent job.
                Predefined function omp_get_thread_num() is used to print the thread id. 

Watch following video:



                Go through the following program:




Program: (openmpsections.c)

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

void main()
{
  #pragma omp parallel sections num_threads(3)
   {
     #pragma omp section
      {
        int tid;
        tid=omp_get_thread_num();
        printf("X printed by thread with id=%d\n",tid);
      }
     #pragma omp section
      {
        int tid;
        tid=omp_get_thread_num();
        printf("Y printed by thread with id=%d\n",tid);
      }
     #pragma omp section
      {
        int tid;
        tid=omp_get_thread_num();
        printf("Z printed by thread with id=%d\n",tid);
      }
   }
}

How To Run: 
To Compile:
gcc -fopenmp openmpsections.c   

To Run:
./a.out

Output: 




No comments:

Post a Comment