Skip to content

Unit 10 · Task Parallelism

3 h contact · 6 h self study Prerequisites: Unit 9 CLO 4

1. Setting the scene

Scenario: The nightly pipeline is not a loop

The SensorGrid nightly job is really a workflow: load the air quality file and the traffic file, clean each of them, join and analyse them, then write the report. Each step is a function, and some steps take much longer than others. A parallel for does not fit: there is no loop to split.

Guiding questions

  1. How do we express "these functions may run at the same time"?
  2. Which steps can really overlap, and which must wait for others?
  3. How much faster can a workflow become, at best?

2. Intended learning outcomes

# Outcome Bloom CLO
ILO 10.1 Contrast data parallelism and task parallelism. UNDERSTAND 4
ILO 10.2 Create tasks with task, single and taskwait. APPLY 4
ILO 10.3 Model a workflow as a dependency graph and express it with depend clauses. APPLY 4
ILO 10.4 Compute work, span and the achievable parallelism of a task graph. ANALYSE 1

3. Recap: two ways to divide work

Each teaching assistant does the same type of work (task) on different sheets (data).

flowchart LR
    D["300 exams"] --> A["TA 1: grade exams 1 to 100"]
    D --> B["TA 2: grade exams 101 to 200"]
    D --> C["TA 3: grade exams 201 to 300"]

Each teaching assistant does a different type of work on the same sheets.

flowchart LR
    D["each exam"] --> A["TA 1: questions 1 to 5"]
    D --> B["TA 2: questions 6 to 10"]
    D --> C["TA 3: questions 11 to 15"]

4. Task based parallelism in OpenMP

Goal: go beyond parallel for and model real workflows. Many real programs are not loop based: the work consists of independent tasks with different execution times.

OpenMP tasks let us express what can run in parallel, not how.

Problem statement

flowchart LR
    L["Load data<br/>disk or network"] --> C["Clean and<br/>preprocess"] --> A["Analyse"] --> W["Write results<br/>to storage"]

Sequential execution

load_data();
clean_data();
analyze_data();
write_output();

Simple and easy to reason about, but it uses one core and wastes the available parallelism.

Parallel thinking with tasks

We describe tasks, not threads. Each task is a unit of work; tasks can run concurrently; the runtime decides when and where they execute. This matches real data pipelines.

#pragma omp parallel
#pragma omp single
{
    #pragma omp task
    load_data();
    #pragma omp task
    clean_data();
    #pragma omp task
    analyze_data();
    #pragma omp task
    write_output();
}
  • parallel creates the team of threads;
  • single makes one thread create the tasks (otherwise every thread would create all four);
  • task defines an independent unit of work; tasks may execute concurrently on any thread of the team.

What happens at run time?

sequenceDiagram
    participant P as Producer thread (single)
    participant Q as Task pool
    participant W1 as Worker 1
    participant W2 as Worker 2
    P->>Q: create task load_data
    P->>Q: create task clean_data
    P->>Q: create task analyze_data
    P->>Q: create task write_output
    W1->>Q: take load_data
    W2->>Q: take clean_data
    P->>Q: take analyze_data
    W1->>Q: take write_output
    Note over P,W2: implicit barrier at the end of the parallel region

The runtime creates a pool of worker threads, schedules tasks dynamically, and balances the load automatically. No manual thread management is needed.

5. Why task based parallelism matters

It matches real systems. Modern workloads are workflows, not loops:

Domain Workflow
ETL load → clean → analyse → store
IoT and edge ingest → filter → detect events → act
Data science preprocessing, feature extraction, model scoring

Not every problem is a for loop; tasks express independent units of work directly, so the code structure reflects the problem structure.

It improves efficiency and scalability. Tasks with unequal execution times are scheduled dynamically, which reduces idle cores; more available tasks mean better core utilisation on many core CPUs.

Parallelism is about structure, not syntax.

6. Dependencies: the honest version

Discussion: which tasks could really run in parallel?

In reality, clean_data needs the loaded data, analyze_data needs clean data, and write_output needs the results. The four tasks in Section 4 depend on each other; launched as independent tasks, they would produce wrong results. How is this different from parallel for, where iterations were independent by construction?

The solution: describe the dependencies and let the runtime respect them. For SensorGrid, two input files can be loaded and cleaned independently:

flowchart LR
    LA["load A<br/>0.3 s"] --> CA["clean A<br/>0.2 s"]
    LB["load B<br/>0.3 s"] --> CB["clean B<br/>0.2 s"]
    CA --> AN["analyse<br/>0.3 s"]
    CB --> AN
    AN --> WR["write output<br/>0.1 s"]
#include <omp.h>
#include <stdio.h>
#include <unistd.h>

static double t0;
static void step(const char *name, int ms) {
    usleep(ms * 1000);                               /* stands in for real work */
    printf("%-14s thread %d  t = %.2f s\n", name, omp_get_thread_num(), omp_get_wtime() - t0);
}

int main(void) {
    char raw_a, raw_b, clean_a, clean_b, stats;      /* dependency tokens only */
    t0 = omp_get_wtime();
    #pragma omp parallel
    #pragma omp single
    {
        #pragma omp task depend(out: raw_a)
        step("load A", 300);
        #pragma omp task depend(out: raw_b)
        step("load B", 300);
        #pragma omp task depend(in: raw_a) depend(out: clean_a)
        step("clean A", 200);
        #pragma omp task depend(in: raw_b) depend(out: clean_b)
        step("clean B", 200);
        #pragma omp task depend(in: clean_a, clean_b) depend(out: stats)
        step("analyse", 300);
        #pragma omp task depend(in: stats)
        step("write output", 100);
        #pragma omp taskwait
    }
    printf("total %.2f s (sequential: 1.40 s)\n", omp_get_wtime() - t0);
    return 0;
}
load A         thread 0  t = 0.30 s
load B         thread 3  t = 0.30 s
clean B        thread 3  t = 0.50 s
clean A        thread 0  t = 0.50 s
analyse        thread 0  t = 0.80 s
write output   thread 0  t = 0.90 s
total 0.90 s (sequential: 1.40 s)
gantt
    title Execution with dependencies on 2 threads
    dateFormat X
    axisFormat %s
    section Thread 0
    load A :0, 3
    clean A :3, 5
    analyse :5, 8
    write :8, 9
    section Thread 1
    load B :0, 3
    clean B :3, 5

(time axis in tenths of a second)

7. How fast can a task graph be? Work and span

  • Work \(T_1\): total time of all tasks (the time on one thread).
  • Span \(T_\infty\): length of the longest dependency chain, the critical path (the time with unlimited threads).
\[ \text{parallelism} = \frac{T_1}{T_\infty}, \qquad \max\!\left(\frac{T_1}{p},\; T_\infty\right) \;\le\; T_p \;\le\; \frac{T_1}{p} + T_\infty \]

The upper bound (Brent's theorem) holds for a greedy scheduler such as the OpenMP runtime.

Worked example: the SensorGrid DAG

\(T_1 = 0.3 + 0.3 + 0.2 + 0.2 + 0.3 + 0.1 = 1.4\) s. Critical path: load A → clean A → analyse → write \(= 0.3 + 0.2 + 0.3 + 0.1 = 0.9\) s.

\[ \text{parallelism} = \frac{1.4}{0.9} \approx 1.56 \]

No number of threads can finish this workflow in less than 0.9 s; beyond two threads there is nothing left to gain. To go faster we must shorten the critical path, for example by splitting analyse into per district tasks.

8. Recursive tasks

Tasks can create tasks. This is natural for divide and conquer algorithms, trees and graphs:

long fib(int n) {
    if (n < 20) {                          /* cut off: small problems run serially */
        long a = 0, b = 1;
        for (int i = 0; i < n; i++) { long t = a + b; a = b; b = t; }
        return a;
    }
    long x, y;
    #pragma omp task shared(x)
    x = fib(n - 1);
    #pragma omp task shared(y)
    y = fib(n - 2);
    #pragma omp taskwait                  /* wait for both children */
    return x + y;
}
flowchart TB
    F5["fib(n)"] --> F4["task: fib(n−1)"]
    F5 --> F3["task: fib(n−2)"]
    F4 --> F3b["task: fib(n−2)"]
    F4 --> F2["task: fib(n−3)"]
    F3 --> F2b["task: fib(n−3)"]
    F3 --> F1["task: fib(n−4)"]

The cut off matters: creating a task costs microseconds, so tiny tasks would cost more to manage than to compute.

9. Classwork

Design a task graph (25 min)

The SensorGrid alert pipeline has these steps (times in ms): read batch (40), decode JSON (30), validate (20), enrich with sensor metadata (50, needs the metadata cache loaded once: 60), detect anomalies (40, needs validated and enriched data), publish alerts (10), archive raw batch (70, needs only the read batch).

  1. Draw the dependency graph.
  2. Compute \(T_1\), \(T_\infty\) and the parallelism.
  3. Write the OpenMP task code with depend clauses.
Solution sketch

Chains: read → decode → validate; read → decode → enrich (also after metadata); validate and enrich → detect → publish; read → archive. \(T_1 = 40+30+20+50+60+40+10+70 = 320\) ms. Critical path: read(40) → decode(30) → enrich(50) → detect(40) → publish(10) \(= 170\) ms (metadata runs in parallel from time 0 and is ready at 60 ms, before decode finishes at 70 ms). Parallelism \(= 320 / 170 \approx 1.9\).

10. Check your understanding

Why do we need single when creating tasks inside a parallel region?

Without it, every thread in the team would execute the task creation code, creating each task once per thread.

What does taskwait wait for?

For the completion of the child tasks created by the current task (not grandchildren).

A DAG has work 10 s and span 2 s. Bound the time on 4 threads.

\(\max(10/4, 2) = 2.5 \le T_4 \le 10/4 + 2 = 4.5\) s.

11. Key takeaways

  • Data parallelism: same task, different data. Task parallelism: different tasks, possibly the same data.
  • OpenMP tasks describe what may run in parallel; the runtime schedules them dynamically.
  • Real workflows have dependencies: express them with depend or taskwait.
  • Work and span bound performance: \(T_p \ge \max(T_1/p, T_\infty)\); shorten the critical path to go faster.

Portfolio option: express a multi stage SensorGrid pipeline as OpenMP tasks, draw its DAG, compute work and span, and compare the measured time with the bounds.

Further reading

  • O. Louant, OpenMP training, CISM/CÉCI.
  • R. D. Blumofe, C. E. Leiserson (1999), Scheduling multithreaded computations by work stealing, JACM 46(5).