The Parallel Directive

The parallel for/do directive is useful, but limited. It only allows for/do loops, and prohibits early termination. The parallel directive is much more general. This directive launches a team of threads. Execution within the parallel region is replicated among all the threads.

Do/while loops are permitted and may contain breaks or exits.

Syntax:

C/C++

#pragma omp parallel {}

Example

Contents of omp_parallel.c
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>

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

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

Download omp_parallel.c file

Fortran

!$omp parallel
!$omp end parallel

Reminder to Fortran programmers: Fortran parallel regions often require a private clause because most Fortran programs do not use block statements and variables are not declared within the parallel region.

Example

Contents of omp_parallel.f90
program omp_par
use omp_lib

   integer :: tid

   !$omp parallel private(tid)
   tid=omp_get_thread_num()
   write(*,'(a,i4)') "Hello from thread ",tid
   !$omp end parallel

end program

Download omp_parallel.f90 file

kkkk Python (for omp4py)

with omp("parallel")

Example

Contents of omp_parallel.py
from omp4py import *

@omp
def hello():
    with omp("parallel"):
        tid=omp_get_thread_num()
        print(f"Hello from thread {tid}")
    
hello()

Download omp_parallel.py file

Previous
Next
© 2026 The Rector and Visitors of the University of Virginia