B8 - parallel sections
#pragma omp parallel sections
{
#pragma omp section
{
// Task A
}
#pragma omp section
{
// Task B
}
#pragma omp section
{
// Task C
}
}
- threads execute different independent blocks of code
parallelcreates a team of threads.sectionsdistributes the sections among those threads.- each
sectionis executed exactly once by one thread in the team. - a thread can execute more than one section, but a single section is never divided among multiple threads
- variables declared outside the parallel region are shared by default
- by default OpenMP places an implicit barrier at the end of the
sectionsconstruct - can use
nowaiton asectionsconstruct to remove its end barrier when it is inside an existing parallel region
#pragma omp parallel
{
#pragma omp sections nowait
{
#pragma omp section
{
taskA();
}
#pragma omp section
{
taskB();
}
}
// Other work
}
-
it may have several clauses, similar to
for -
eg:
private(x),firstprivate(x),lastprivate(x),reduction(op:x) -
however, scheduling cannot be influenced
invalid implementations
#pragma omp parallel private(tid)
{
tid = omp_get_thread_num();
if (tid != 0) {
#pragma omp sections
{
f = funk();
#pragma omp section
g = gunk();
}
}
else {
h = hunk();
}
}
- thread 0 skips the
sectionsconstruct entirely while the others encounter it - this is invalid because
omp sectionsis a work-sharing construct that binds to the enclosing parallel team - all threads in that team must encounter it
- the correct implementation would be:
#pragma omp parallel private(tid)
{
tid = omp_get_thread_num();
#pragma omp sections
{
#pragma omp section
{
f = funk();
}
#pragma omp section
{
g = gunk();
}
}
if (tid == 0) {
h = hunk();
}
}
- all threads encounter the same
sectionsconstruct - after the sections finish thread 0 executes
hunks()