Task Decomposition Algorithm Strategies

All threaded programs have some form of task decomposition, that is, delineating which threads will do what tasks in parallel at certain points in the program. We have seen one way of dictating this by using the master-worker implementation, where one thread does one task and all the others to another. Here we introduce a more general approach that can be used.

16. Task Decomposition Algorithm Strategy using OpenMP section directive

file: openMP/16.sections/sections.c

Build inside 16.sections directory:

make sections

Execute on the command line inside 16.sections directory:

./sections

This example shows how to create a program with arbitrary separate tasks that run concurrently. This is useful if you have tasks that are not dependent on one another.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/* sections.c
 * ... illustrates the use of OpenMP's parallel section/sections directives,
 *      which can be used for task parallelism...
 *
 * Joel Adams, Calvin College, November 2009.
 *
 * Usage: ./sections
 *
 * Exercise: Compile, run (several times), compare output to source code.
 */

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

int main(int argc, char** argv) {

    printf("\nBefore...\n\n");

    #pragma omp parallel sections num_threads(4)
    {
        #pragma omp section 
        {
            printf("Task/section A performed by thread %d\n", 
                    omp_get_thread_num() ); 
        }
        #pragma omp section 
        {
            printf("Task/section B performed by thread %d\n",
                    omp_get_thread_num() ); 
        }
        #pragma omp section
        {
            printf("Task/section C performed by thread %d\n",
                    omp_get_thread_num() ); 
        }
        #pragma omp section 
        {
                printf("Task/section D performed by thread %d\n", 
                         omp_get_thread_num() ); 
        }
    }

    printf("\nAfter...\n\n");

    return 0;
}