It is easy to understand the concurrency model of OpenMP when viewed in the context of the corresponding Pthreads translation. In Figure 5.1, one possible translation of an OpenMP program to a Pthreads program is shown (such a translation can easily be automated through a Yacc or CUP script).
#include <omp.h>
main () {
int var1, var2, var3;
Serial code
.
.
Beginning of parallel section. Fork a team of threads.
Specify variable scoping
#pragma omp parallel private(var1, var2) shared(var3)
{
Parallel section executed by all threads
.
.
All threads join master thread and disband
}
Resume serial code
.
.
}
************
#include <omp.h>
int a,b,num_threads;
int main()
{
printf("I am in sequential part.\n");
#pragma omp parallel num_threads (8) private (a) shared (b)
{
num_threads=omp_get_num_threads();
printf("I am openMP parellized part and thread %d \n",omp_get_thread_num());
}
}
Using the parallel directive
1 #pragma omp parallel if (is_parallel == 1) num_threads(8) \
2 private (a) shared (b) firstprivate(c)
3 {
4 /* structured block */
5 }
Here, if the value of the variable is_parallel equals one, eight threads are created. Each of these threads gets private copies of variables a and c, and shares a single value of variable b. Furthermore, the value of each copy of c is initialized to the value of c before the parallel directive.