Rookie HPC

Tasking

C | FORTRAN

task

Definition

The task clause creates an explicit task encapsulating the structured block assigned. It will either be executed immediately by the thread that encountered the task clause, either deferred and executed by any thread in the team. There are two ways with which one can wait for the completion of tasks: barrier and taskwait.

Copy

Feedback

#pragma omp task [if([task:] scalar-expression)]
                 [final(scalar-expression)]
                 [untied]
                 [default(policy)]
                 [mergeable]
                 [private(list)]
                 [firstprivate(list)]
                 [shared(list)]
                 [in_reduction([modifier,] identifier: list)]
                 [depend([modifier,] type: list)]
                 [priority(priority-value)]
                 [allocate([allocator:] list)]
                 [affinity([modifier:] list)]
                 [detach(event-handle)]

Example

Copy

Feedback

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

/**
 * @brief Illustrates how to create tasks.
 * @details This application consists of a thread, in an OpenMP parallel
 * region, that spawns tasks.
 **/
int main(int argc, char* argv[])
{
    // Use 3 threads when creating OpenMP parallel regions
    omp_set_num_threads(3);

    // Create the parallel region
    #pragma omp parallel
    {
        // One thread will spawn the tasks
        #pragma omp single
        {
            // Spawn the first task
            #pragma omp task
            {
                printf("Task 1 executed by thread %d.\n", omp_get_thread_num());
            }

            // Spawn the second task
            #pragma omp task
            {
                printf("Task 2 executed by thread %d.\n", omp_get_thread_num());
            }
        }
    }

    return EXIT_SUCCESS;
}