We will start with:
Parallel construct
Work-sharing construct
In OpenMP, the most important one of
all basic features, is parallel construct. It plays a crucial role
in OpenMP. This construct is used to specify the computations that
should be executed in parallel.
There is just one library function
should be taken care-omp_get_thread_num( ).
Sharing the work among threads in an
OpenMP program
This important feature is used to
distribute computation among the threads in a team.
C/C++ has three work-sharing
constructs:
Distribute iterations over the
threads--#pragma omp for
Distribute independent work
units--#pragma omp sections
Only one thread executes the code
block--#pragma omp single
There are two main rules regarding
work-sharing constructs:
Each work-sharing region must be
encountered by all threads in a team or by none at all.
The sequence of work-sharing regions
and barrier regions encountered must be the same for every thread
in a team.
Next I will describe these
constructs.
1.
Loop Construct
We need to remember the syntax of the
loop construct in C/C++:
#pragma omp for
For-loop
An example:
#pragma omp parallel
{
#pragma omp for
For(…)
…
}
2.
The Sections Construct
This construct is the easiest way to
get different threads to carry out different kinds of work, since
it permits us to specify several different code regions, each of
which will be executed by one of the threads.
It consist of two directives: #pragma
omp sections and #pragma omp section
An example:
#pragma omp parallel
{
#pragma omp setions
{
#pragma omp setion
Void funcA();
#pragma omp setion
Void funcB();
}
}
Something should be noted.
If only one thread is available, both
calls to funcA and funcB are executed in parallel, but in
sequential order.
One cannot make any assumption on the
specific order in which section blocks are executed. Even if these
calls are executed sequentially.
3.
The Single Construct
The single construct is associated
with the structured block of code immediately following it and
specifies that this block should be executed by one thread
only.
Note: it does not state which thread
should execute the code block.
And the syntax of this construct in
C/C++ is:
#pragma omp single
An example:
#pragma omp parallel
{
#prama omp single
{
}
#pragma omp for
For ( … )
}
Only one thread execute the single
section.
4.
Combined Parallel Work-Sharing
Constructs
Combined parallel work-sharing
constructs are shortcuts that can be used when a parallel region
comprises precisely one work-sharing construct, that is, the
work-sharing region includes all the code in the parallel
region.
For example:
There are advantages of using
shortcuts. One is readability, and another is a performance
advantage.