Parallelize a Loop with
Turn a serial C loop into a multithreaded one with one OpenMP pragma, then learn which loops are safe to split and which ones silently give wrong answers.

A loop that does the same independent work on every element is the easiest thing in a program to run on several cores, and OpenMP lets you do it by adding one line above the loop. No thread creation, no joining, no queue. The line is #pragma omp parallel for, and it works because the compiler turns it into calls into an OpenMP runtime that owns a pool of threads. This post uses OpenMP 4.5 semantics, GCC 14 and Linux, and shows the smallest complete program, what the pragma actually does, and the single rule that decides whether your loop is safe to split. The OpenMP guide for this series covers the wider picture; here the goal is one loop, done correctly.
The smallest complete program
Start with a loop that squares every element of an array. Each iteration reads one slot and writes the same slot, so no iteration depends on any other.
#include <stdio.h>
#include <omp.h>
#define N 8
int main(void) {
int a[N];
#pragma omp parallel for
for (int i = 0; i < N; i++) {
a[i] = i * i;
}
for (int i = 0; i < N; i++) {
printf("a[%d] = %d\n", i, a[i]);
}
return 0;
}Build it with gcc -fopenmp -O2 squares.c -o squares. Without -fopenmp the compiler ignores the pragma and you get a correct serial program, which is by design: the pragma is a hint to a compiler that understands it, and a comment to one that does not.
a[0] = 0
a[1] = 1
a[2] = 4
a[3] = 9
a[4] = 16
a[5] = 25
a[6] = 36
a[7] = 49The output is the same on every run, because the second loop is serial and prints in index order after all the writes finished. The parallel loop has an implicit barrier at its end: no thread leaves it until all threads have finished their share. That barrier is why the printing loop can safely read a.
What the pragma expands into
parallel for is a shorthand for two directives. parallel forks a team of threads, and for splits the iterations of the loop that follows among them. You can write them separately, and doing so is how you run several loops in one team and avoid forking twice.
#include <stdio.h>
#include <omp.h>
#define N 8
int main(void) {
int a[N], b[N];
#pragma omp parallel
{
#pragma omp for
for (int i = 0; i < N; i++) a[i] = i * i;
#pragma omp for
for (int i = 0; i < N; i++) b[i] = a[i] + 1;
}
printf("b[7] = %d\n", b[7]);
return 0;
}b[7] = 50The first omp for ends with its own barrier, so every a[i] is written before any thread starts the second loop. Remove that barrier with the nowait clause and the second loop could read a slot that no thread has written yet. Keep the default until you have a reason and a proof.
The number of threads comes from the OMP_NUM_THREADS environment variable, or from the machine's logical CPU count when it is unset. You can see the team at work by asking each thread for its number.
#include <stdio.h>
#include <omp.h>
int main(void) {
int owner[8];
#pragma omp parallel for num_threads(4)
for (int i = 0; i < 8; i++) {
owner[i] = omp_get_thread_num();
}
for (int i = 0; i < 8; i++) {
printf("iteration %d ran on thread %d\n", i, owner[i]);
}
return 0;
}iteration 0 ran on thread 0
iteration 1 ran on thread 0
iteration 2 ran on thread 1
iteration 3 ran on thread 1
iteration 4 ran on thread 2
iteration 5 ran on thread 2
iteration 6 ran on thread 3
iteration 7 ran on thread 3With no schedule clause the split is implementation-defined, and GCC's libgomp divides the range into one contiguous block per thread. Do not write code that depends on that. The point of the sample is the mapping: eight iterations, four threads, two each. How to change the split is the subject of choosing OpenMP schedules.
The rule that decides whether a loop is safe
OpenMP does not check your loop. It splits iterations and trusts you that they are independent. A loop is safe to split when no iteration reads a location that another iteration writes, and no two iterations write the same location. That is the whole rule, and every parallel-loop bug is a violation of it.
Here is the classic violation, a running total.
#include <stdio.h>
#include <omp.h>
int main(void) {
long sum = 0;
#pragma omp parallel for
for (int i = 1; i <= 1000000; i++) {
sum += i;
}
printf("sum = %ld\n", sum);
return 0;
}The correct answer is 500000500000. This program has a data race on sum: every thread loads it, adds, and stores it back, and two threads can load the same old value, so one update disappears. It compiles cleanly and runs without complaint.
sum = 311872204518The number you get differs on every run and on every machine, and that is the usual shape of the symptom: a plausible value that changes. Never accept a parallel result you did not compare against the serial one at least once. The fix for accumulations is the reduction clause, which gives each thread a private copy and combines them at the end; combining results with the reduction clause walks through it.
Other loops fail the rule in less obvious ways.
| Loop body | Why it is not safe to split |
|---|---|
a[i] = a[i-1] + 1 | Iteration i reads what iteration i-1 writes |
total += x[i] | Every iteration writes total |
if (x[i] == key) { found = i; break; } | break is not allowed inside a parallel for |
idx = next++; out[idx] = f(i) | Shared counter, order of results undefined |
printf inside the body | Safe from corruption, but output order is arbitrary |
The break case is not a race but a compile error: the OpenMP specification requires the loop in a worksharing construct to be in canonical form, which rules out break, goto out of the loop, and a modified loop variable in the body. The canonical form also requires the trip count to be known when the loop starts, which is why for (int i = 0; i < n; i++) works and while loops do not.
Make private what each iteration owns
Variables declared inside the loop body are private to each iteration by construction. Variables declared before the loop are shared by default, which is the source of most mistakes. This version has a bug that looks harmless.
#include <stdio.h>
#include <omp.h>
#define N 1000
int main(void) {
double out[N];
double t;
#pragma omp parallel for
for (int i = 0; i < N; i++) {
t = i * 0.5;
out[i] = t * t;
}
printf("out[999] = %.2f\n", out[999]);
return 0;
}t is declared outside the loop, so it is shared. One thread can store t, another thread overwrites it, and the first thread then squares the wrong value. The fix is to move the declaration into the loop, or to name it in a private(t) clause. Declaring at the point of first use is cleaner, and C99 and later let you do it.
#include <stdio.h>
#include <omp.h>
#define N 1000
int main(void) {
double out[N];
#pragma omp parallel for
for (int i = 0; i < N; i++) {
double t = i * 0.5;
out[i] = t * t;
}
printf("out[999] = %.2f\n", out[999]);
return 0;
}out[999] = 249500.25The loop variable i is private automatically, one of the few variables OpenMP privatizes for you. For anything else, scoping variables with private, firstprivate and default(none) gives a rule you can apply mechanically so the question never comes up.
When the pragma does not pay
Forking a team and joining it costs time, and that cost is paid on every execution of the pragma. A loop of eight iterations that each do a multiplication is slower in parallel, not faster. The if clause turns the parallel region off at run time when the loop is too small to be worth it.
#include <stdio.h>
#include <omp.h>
void scale(double *x, int n, double k) {
#pragma omp parallel for if(n > 10000)
for (int i = 0; i < n; i++) {
x[i] *= k;
}
}
int main(void) {
double v[4] = {1.0, 2.0, 3.0, 4.0};
scale(v, 4, 2.0);
printf("%.1f %.1f %.1f %.1f\n", v[0], v[1], v[2], v[3]);
return 0;
}2.0 4.0 6.0 8.0The threshold 10000 is a placeholder. The right value depends on the loop body and your machine, and you find it by measuring on the target hardware, never by guessing. Memory-bound loops, such as the scaling loop above, also stop speeding up once the cores saturate memory bandwidth, so more threads do not mean more speed.
This post is for loops written in C. If your loop is in Rust, parallelizing iterators with Rayon reaches the same result with the borrow checker enforcing the independence rule for you.
For the authoritative option and behavior details, see the OpenMP specifications.


