Rookie HPC

Work sharing

C | FORTRAN

sections

Definition

The sections clause is a worksharing construct; the section clauses that are contained in it will be picked and executed by the threads in the team. If the sections clause is not associated with a nowait clause, an implicit barrier takes place at the end; waiting for all section clauses contained to complete.

Copy

Feedback

#pragma omp sections [private(list)]
                     [firstprivate(list)]
                     [lastprivate([modifier:] list)]
                     [reduction([modifier,] identifier: list)]
                     [allocate([allocator:] list)]
                     [nowait]

Example

Copy

Feedback

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

/**
 * @brief Illustrates how to use a sections clause.
 * @details A parallel region is created, in which a sections worksharing
 * construct is built, containing multiple section clauses defining jobs to do
 * by threads.
 **/
int main(int argc, char* argv[])
{
    // Use 4 threads when creating OpenMP parallel regions
    omp_set_num_threads(4);

    // Create the parallel region
    #pragma omp parallel
    {
        // Create the sections
        #pragma omp sections
        {
            // Generate the first section
            #pragma omp section
            {
                printf("Section 1 is executed by thread %d.\n", omp_get_thread_num());
            }

            // Generate the second section
            #pragma omp section
            {
                printf("Section 2 is executed by thread %d.\n", omp_get_thread_num());
            }
        }
    }

    return EXIT_SUCCESS;
}