Skip to content
systemcoding.dev
Concurrency

Use OpenMP Tasks for Recursive Parallelism

Parallelize recursive C code such as Fibonacci and tree walks with OpenMP tasks, taskwait and a cutoff, and see why a task per call runs slower than serial.

7 min read
Summarize in AI
Flat illustration of parallel threads meeting at a mutex, with the C, Rust and Erlang logos.

A parallel for needs an index range it can split before the loop starts. Recursive code has no such range: the work is a tree that unfolds as the program runs, and the second half of a split does not exist until the first half has been examined. OpenMP tasks are the construct for that shape. A task is a unit of work you hand to the runtime, which runs it on some thread in the team at some later time. This post uses OpenMP 4.5 on GCC 14, writes a parallel Fibonacci and a parallel tree sum, and spends most of its length on the part tutorials skip: a task per call makes the program slower than serial, and a cutoff fixes it. If you have not yet met parallel for, start with parallelizing a loop with a pragma.

The three pieces: parallel, single, task

Tasks need a team of threads to run on, so the region starts with parallel. One thread must create the first task, so the body is wrapped in single. Everything else follows from task and taskwait.

fib-tasks.cc
#include <stdio.h>
#include <omp.h>

static long fib_serial(int n) {
    return n < 2 ? n : fib_serial(n - 1) + fib_serial(n - 2);
}

static long fib(int n) {
    if (n < 20) return fib_serial(n);

    long x, y;

    #pragma omp task shared(x)
    x = fib(n - 1);

    #pragma omp task shared(y)
    y = fib(n - 2);

    #pragma omp taskwait
    return x + y;
}

int main(void) {
    long result = 0;

    #pragma omp parallel
    {
        #pragma omp single
        result = fib(30);
    }

    printf("fib(30) = %ld\n", result);
    return 0;
}
Text
fib(30) = 832040

Walk through what each line does. parallel forks the team and every thread enters the block. single lets exactly one thread, whichever arrives first, call fib(30); the others skip to the end of the single, where they wait and become available to run tasks. Inside fib, each #pragma omp task packages the next statement as a task and returns immediately. The calling thread does not run it right away; the task goes into a pool. taskwait makes the current task wait until its child tasks, the two it just created, have completed. Without it, x + y would read two variables nobody had written yet.

The shared(x) clause is needed because variables in a task are firstprivate by default when they are not shared in the enclosing context. Here x lives on the stack of the creating call, and the creating call waits at taskwait before leaving, so the stack frame outlives the tasks. That is the rule that makes sharing stack variables legal: a task may use a stack variable by reference only if something guarantees the frame stays alive until the task finishes. taskwait is that guarantee.

Why the cutoff is not optional

Creating a task costs far more than a function call, because the runtime allocates a task descriptor, copies captured variables and enqueues it. fib(n - 2) for n near 2 does almost no work, so a task per call spends nearly all its time on bookkeeping. The line if (n < 20) return fib_serial(n); stops creating tasks once the subproblem is small and finishes it in a plain recursive call.

Compare it to the naive version.

fib-naive.cc
#include <stdio.h>
#include <omp.h>

static long fib(int n) {
    if (n < 2) return n;

    long x, y;

    #pragma omp task shared(x)
    x = fib(n - 1);

    #pragma omp task shared(y)
    y = fib(n - 2);

    #pragma omp taskwait
    return x + y;
}

int main(void) {
    long result = 0;

    #pragma omp parallel
    {
        #pragma omp single
        result = fib(30);
    }

    printf("fib(30) = %ld\n", result);
    return 0;
}
Text
fib(30) = 832040

Same answer, and for fib(30) it creates over a million tasks, nearly all of them trivial. We do not print a time here because the figure depends on your hardware; the experiment that matters is cheap to run yourself: time this file against a serial fib, and then against fib-tasks.c. The naive version is routinely slower than the serial one, and the cutoff version is the only one that wins. The cutoff value, 20 here, is a tuning parameter. A good starting point is a size where the serial subproblem takes on the order of tens of microseconds, and you find the exact spot by measuring.

OpenMP also gives you clauses that do the cutoff for you, with different semantics.

fib-final.cc
#include <stdio.h>
#include <omp.h>

static long fib(int n) {
    if (n < 2) return n;

    long x, y;

    #pragma omp task shared(x) final(n <= 20)
    x = fib(n - 1);

    #pragma omp task shared(y) final(n <= 20)
    y = fib(n - 2);

    #pragma omp taskwait
    return x + y;
}

int main(void) {
    long result = 0;

    #pragma omp parallel
    {
        #pragma omp single
        result = fib(30);
    }

    printf("fib(30) = %ld\n", result);
    return 0;
}
Text
fib(30) = 832040

final(expr) says that when the expression is true, the task is a final task, and every task it generates is executed immediately as an included task, meaning no new queued tasks. That keeps the whole subtree on one thread without the call to a separate serial function. It is more convenient and a little slower than the hand-written serial function, because the final path still goes through the task-creation code. The related if(expr) clause makes only the one task undeferred, and its children still go to the queue, so for recursion final is the right clause and if is not.

Walking a tree

Recursive tree algorithms are the other home of tasks: the shape is not a range, and the two subtrees are independent. This sums the values of a binary tree.

tree-sum.cc
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int value;
    struct Node *left, *right;
} Node;

static Node *make(int value, Node *l, Node *r) {
    Node *n = malloc(sizeof *n);
    n->value = value; n->left = l; n->right = r;
    return n;
}

static long sum_serial(const Node *n) {
    return n ? n->value + sum_serial(n->left) + sum_serial(n->right) : 0;
}

static long sum(const Node *n, int depth) {
    if (!n) return 0;
    if (depth >= 3) return sum_serial(n);

    long l = 0, r = 0;

    #pragma omp task shared(l) firstprivate(n, depth)
    l = sum(n->left, depth + 1);

    #pragma omp task shared(r) firstprivate(n, depth)
    r = sum(n->right, depth + 1);

    #pragma omp taskwait
    return n->value + l + r;
}

int main(void) {
    Node *root = make(1,
        make(2, make(4, NULL, NULL), make(5, NULL, NULL)),
        make(3, make(6, NULL, NULL), make(7, NULL, NULL)));
    long total = 0;

    #pragma omp parallel
    {
        #pragma omp single
        total = sum(root, 0);
    }

    printf("sum of 1..7 = %ld\n", total);
    return 0;
}
Text
sum of 1..7 = 28

Two details. The cutoff here is by depth, because a tree's subtree sizes are not known in advance and depth is cheap. For a balanced tree, a cutoff depth near log2 of the number of threads times a small factor gives enough tasks to keep every thread busy without drowning the queue. And firstprivate(n, depth) copies the pointer and the depth into the task at creation time; without it the default rules would make n firstprivate anyway, but writing it removes the doubt for the reader.

Tasks and the loop that creates them

A different shape is a loop that generates tasks, for example one per list element when the iteration cannot be an index range. The generating thread creates the tasks while the others run them.

list-tasks.cc
#include <stdio.h>
#include <omp.h>

#define N 6

int main(void) {
    int squares[N];

    #pragma omp parallel
    {
        #pragma omp single
        {
            for (int i = 0; i < N; i++) {
                #pragma omp task firstprivate(i) shared(squares)
                squares[i] = i * i;
            }
        }
    }

    for (int i = 0; i < N; i++) printf("%d ", squares[i]);
    printf("\n");
    return 0;
}
Text
0 1 4 9 16 25 

The tasks finish at the implicit barrier at the end of the parallel region, which also waits for all outstanding tasks, so no explicit taskwait is needed before the printing loop. If the index range is known, #pragma omp taskloop (OpenMP 4.5) does the same with chunking handled for you, and a plain parallel for is simpler still. Use the loop-generating form only when you cannot express the work as a counted loop.

Where tasks go wrong

  • **Forgetting single.** Without it, every thread executes fib(30) and you compute the answer once per thread.

  • **Reading before taskwait.** The result variables are not set until the child tasks finish.

  • Sharing a variable that outlives its frame. A task capturing a pointer to a stack variable from a function that has already returned is a use-after-return. taskwait or a barrier must come before the frame dies.

  • No cutoff. Task overhead dwarfs the work. The cure is a depth, size or final threshold.

  • Shared mutable state in the task body. Tasks run concurrently, so a task that appends to a shared list races exactly like iterations of a loop; see scoping variables with private, firstprivate and default(none).

When the workload is a steady stream of equal pieces, a schedule on a loop beats tasks. When the shape is unbalanced and recursive, tasks win, and the runtime balances them by taking tasks from queues that other threads left behind, the mechanism described in how work-stealing schedulers balance parallel tasks.

For the authoritative option and behavior details, see the OpenMP specifications.

Share

Keep reading

Flat illustration of two options weighed side by side, with the C, C++ and Rust logos.
Performance

Spinlocks vs Mutexes: When Spinning Wins

A spinlock burns a core while it waits and a mutex sleeps. Compare their costs, write a correct C11 spinlock, and see when user-space spinning beats a mutex.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.