Rookie HPC

Work sharing

C

for

Definition

The for construct tells OpenMP that the iteration set of the for loop that follows is to be distributed across the threads present in the team. Without the for construct, the entire iteration set of the for loop concerned will be executed by each thread in the team. From a syntactic point of view, note that the for construct must be immediately followed by the for loop; it does not allow curly brackets between it and the for loop.

Copy

Feedback

#pragma omp for [private(list)]
                [firstprivate(list)]
                [lastprivate([modifier:] list)]
                [linear(linear-list [: step])]
                [reduction([modifier,] identifier: list)]
                [schedule([modifier[, modifier]:] kind [, chunk_size])]
                [collapse(n)]
                [ordered[(n)]]
                [nowait]
                [allocate([allocator:] list)]
                [order(concurrent)]

Example

Copy

Feedback

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

/**
 * @brief Illustrates how to use the for construct.
 * @details This application contains a for loop that initialises an array. This
 * for loop is parallelised by using a for construct inside a parallel region.
 **/
int main(int argc, char* argv[])
{
    // Use 2 threads when creating OpenMP parallel regions
    omp_set_num_threads(2);

    int a[10];

    // Spawn the threads
    #pragma omp parallel
    {
        // Tell the threads to share these iterations rather than running the entire iteration set each
        #pragma omp for
        for(int i = 0; i < 10; i++)
        {
            a[i] = i;
        }
    }

    return EXIT_SUCCESS;
}