PX457 · Course contents

OpenMP: Parallel Regions and Work Sharing

Suppose a loop has one million independent iterations. Giving four threads the source code does not, by itself, divide the iterations into four parts. Each thread might run the entire loop. The distinction between creating workers and assigning work is the first idea to make precise in OpenMP.

The memory chapter distinguished shared and distributed address spaces. OpenMP begins with threads in one process sharing memory. Its API consists of compiler directives, runtime routines and environment variables. It is commonly used for multicore CPUs and also includes device-offload facilities beyond this chapter's scope.

1. A parallel region creates a team

The initial thread executes serial code. On encountering a parallel construct, it forms a team and participates as thread zero, the primary thread (called “master” in older material). Every team member executes the region's structured block. At its end the team synchronises, and the encountering thread continues.

one thread → fork → team executes region → join → one thread

This is a logical execution model; a runtime may reuse operating-system threads rather than create and destroy them at every fork/join.

In C/C++ directives begin #pragma omp; in Fortran, !$omp:

#pragma omp parallel default(shared) private(x, y)
{
    /* Every thread executes this block; x and y are per-thread. */
}
!$omp parallel default(shared) private(x, y)
! work executed by each thread
!$omp end parallel

These are directive fragments; x,y must be declared in the enclosing scope. A work-sharing loop has its own loop syntax and constraints. Disabling directive support does not automatically make calls to the OpenMP runtime disappear: those calls still require appropriate linking or conditional compilation.

A team is an execution structure. Follow the initial thread through a complete region, including the point at which it must wait for the others.

One thread opens into a team

Follow the initial thread through fork, concurrent work and join. Try a different requested team size.

Play, pause, or scrub to inspect a moment.

initialjoinT0T1fork: the initial thread participates

Paused. 2 selected team members. The team is forming.

This logical OpenMP region uses exactly the selected team size. The initial thread participates as thread zero. The drawing describes execution structure, not OS thread creation or a guaranteed speedup. ↗

2. Observe the team before assigning useful work

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

int main(void) {
    #pragma omp parallel
    {
        int tid = omp_get_thread_num();
        int count = omp_get_num_threads();
        printf("Hello from thread %d of %d\n", tid, count);
    }
    return 0;
}

tid and count are declared inside the block, so each thread has its own automatic objects. omp_get_thread_num() is a team-local ID in [0,P)[0,P); omp_get_num_threads() reports that team's actual size. Output order is unspecified. Printing is useful for diagnosis, but distorts a performance measurement.

For a GCC installation with OpenMP support:

gcc -O2 -fopenmp hello.c -o hello
OMP_NUM_THREADS=4 ./hello

Clang needs a compatible OpenMP runtime installed; supported flags and features differ across compilers. Three ways to request team sizes are:

export OMP_NUM_THREADS=8
omp_set_num_threads(8);              /* affects subsequent regions */
#pragma omp parallel num_threads(8) /* applies to this region */
{ /* work */ }

These mechanisms have different scopes and precedence; they are not interchangeable settings. Runtime limits, dynamic adjustment and nesting may affect the actual team size. Never assume the default equals the number of physical cores: query what happened and record affinity and allocation when benchmarking.

3. Work-sharing partitions an iteration set

Compare these two fragments:

#pragma omp parallel
{
    for (int i = 0; i < N; ++i) work(i);
}
#pragma omp parallel for
for (int i = 0; i < N; ++i) work(i);

In the first, each of PP threads executes all NN calls: PNPN calls in total. In the second, the work-sharing for assigns each logical iteration to one thread: NN calls in total. parallel for combines team creation with distribution; a for inside an existing parallel region distributes over that team without creating another team.

The same workers, different ownership
parallel: repeatthread 0thread 1parallel for: partitionthread 0thread 1012301230123
For four iterations and two threads, a bare parallel region duplicates the loop. One possible work-sharing assignment divides the four iterations. Each numbered box is one call to work(i), not an execution time; the unspecified schedule need not choose this exact partition. ↗

The loop index associated with the work-sharing loop is private. That does not make every other variable safe. If work(i) writes only to its own output element and reads immutable input, the iterations may be independent. If all iterations update one shared accumulator, dividing iterations creates concurrent conflicting accesses.

Four threads run a parallel region containing an ordinary loop of ten iterations. How many times is the loop body executed?

Track the calls themselves, rather than counting source-code loops. Each arriving tile records which worker executed one iteration.

Who owns each call?

Keep four workers and eight iterations. Change only whether the loop is work-shared.

Play, pause, or scrub to inspect a moment.

01234567T0T1T2T30 of 8 calls executed

Paused. Partitioned execution has completed 0 calls. Each tile records one execution, not a unit of time.

Each moving tile is one call to work(i). A chosen contiguous partition executes eight calls; an ordinary loop inside a parallel region executes eight calls on each of four threads. ↗

Conditional compilation

_OPENMP is defined when OpenMP processing is enabled:

#ifdef _OPENMP
#include <omp.h>
#endif

Guard runtime calls as well if you intend to support a build without the runtime. A serial fallback must still implement the intended computation; ignoring directives cannot repair code whose correctness depended on explicit thread IDs.

Exercises and the next question

  1. Run the two loop fragments with two and four threads. Predict total calls before observing unordered output.
  2. Put two omp for loops inside one parallel region. Explain which construct creates the team and which assigns work.
  3. Measure a pure array kernel without printing, verify its result against a serial version, and record the actual team size.

Workers and iteration owners are now distinct. Variables and synchronisation asks what happens when those owners touch the same storage.

Reference

OpenMP specification index. Examples here use the common host-threading subset; check implementation support for newer facilities.