Reduction

Tasking

C | Fortran-90

task_reduction

Definition

task_reduction is reduction scoping clause that specifies a reduction among tasks.
For each list item, the number of copies is unspecified. Any copies associated with the reduction are initialised before they are accessed by the tasks participating in the reduction. After the end of the region, the original list item contains the result of the reduction.

Copy

Feedback

task_reduction(identifier: list)

Parameters

identifier

The identifier indicating the reduction operation to apply. It is either a user-defined operator or one of the following operators:

  • +: sum.
  • -: difference.
  • *: product.
  • &: bit-wise and.
  • |: bit-wise or.
  • ^: bit-wise exclusive or.
  • &&: logical and.
  • ||: logical or.
  • min: minimum.
  • max: maximum.
list

The list of reduction variables, separated with commas.

Example

Copy

Feedback

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

/**
 * @brief Illustrates how to do a task reduction.
 * @details This example consists in calculating the sum of all elements of an
 * array.
 **/
int main(int argc, char* argv[])
{
    // Use 2 threads when creating OpenMP parallel regions
    omp_set_num_threads(2);

    int total = 0;
    const int ARRAY_SIZE = 10;
    int* myArray = malloc(sizeof(int) * ARRAY_SIZE);
    if(myArray == NULL)
    {
        printf("Cannot allocate the array \"myArray\".\n");
        return EXIT_FAILURE;
    }

    // Initialise the array
    for(int i = 0; i < ARRAY_SIZE; i++)
    {
        myArray[i] = i;
    }

    // Calculate the sum of all elements
    #pragma omp parallel
    {
        #pragma omp single
        {
            #pragma omp taskgroup task_reduction(+: total)
            {
                for(int i = 0; i < ARRAY_SIZE; i++)
                {
                    #pragma omp task in_reduction(+: total)
                    total += myArray[i];
                }
            }
        }
    }

    printf("The sum of all array elements is %d.\n", total);
    free(myArray);

    return EXIT_SUCCESS;
}