~/Getting Started with OpenMP in C Plus Plus

May 14, 2019


OpenMP enables parallel programming in C Plus Plus using compiler directives. To use OpenMP, include its header and compile with the correct flags.

Include OpenMP with

1
#include <omp.h>

Enable it in your code with pragma directives, such as for parallel loops

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include <omp.h>
#include <iostream>

int main() {
    int sum = 0;
    #pragma omp parallel for reduction(+:sum)
    for(int i = 0; i < 100; ++i) {
        sum += i;
    }
    std::cout << sum << std::endl;
    return 0;
}

Compile your code with the -fopenmp flag using g plus plus:

1
g++ -fopenmp example.cpp -o example

OpenMP makes it easier to write multithreaded code in C Plus Plus. Changing the number of threads used is simple with an environment variable

1
export OMP_NUM_THREADS=4

Read the official OpenMP specification for more details.

Tags: [cpp] [parallel] [openmp]