Monday 18 January 2016

OpenMP Critical Section Example

                      In this post, we will see OpenMP Critical Section with Example | How To Synchronize Threads in OpenMP | openmp critical,openmp critical section with example,openmp critical example,how to synchronize threads,openmp synchronize threads.

                     Critical section is the region in program where various threads want to access global variables. In OpenMP, we can avoid such race condition among different threads by using preprocessor directive "#pragma omp critical ". 

Watch following video:



                Lets see a simple C language program (program.c) which uses OpenMP API. Here we will create 300 threads and each thread will try to increment the value of x.




Program: (program.c)

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

void main()
{
int x=0;

#pragma omp parallel num_threads(300)
{
x=x+1;
}

printf("x=%d\n",x);
}



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

To Run:
./a.out


Output:

                 Check above output. We were expecting output as "x=300". But we got "x=297". It is because, in this case, four threads were simultaneously incrementing the value of x. 
                 We can avoid such race condition in OpenMP by using preprocessor directive "#pragma omp parallel critical ".
                  Check following program:

Program: (openmpcritical.c)


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

void main()
{
int x=0;

#pragma omp parallel num_threads(300)
{
#pragma omp critical
{
x=x+1;
}

}

printf("x=%d\n",x);
}

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

To Run:
./a.out

Output: 

                          Here, we got "x=300" because at one instance only one thread was incrementing the value of x.

(Note: By default variables are shared among threads. We can explicitly mention shared(x) to specify x is shared among threads. I want to say "#pragma omp parallel" and "#pragma omp parallel shared(x)" , both carry same meaning).

Next Post: OPENMP program to find prime numbers from range 1 to n by parallel processing (multi-threading)

Previous Post: OpenMP Parallel Sections Example




No comments:

Post a Comment