This is the first OpenMP program, one can write for understanding the parallelization process using OpenMP.
#include"stdio.h"
#include"omp.h"
int main()
{
#pragma omp parallel
{
printf("\nHello World!");
}
printf("\nProgram Exit!\n");
}
First, let us find out how to compile and execute this code.
gcc -fopenmp hello_world.c
The ‘-fopenmp’ option here requests compiler to generate parallel threads for the given code using OpenMP. If we do not provide this option, compiler will ignore all the OpenMP clauses/directives (in this case – ‘#pragma omp parallel’).
To understand what exactly ‘#pragma omp parallel’ does, let us check out the output of this code.
Hello World!
Hello World!
Hello World!
Hello World!
Program Exit!
You might have already observed that “Hello World!” is printed four times where as “Program Exit!” is printed only once. Here, compiler (as instructed/requested by us using ‘-fopenmp’ option) generates multiple threads for the code block under ‘#pragma omp parallel’. This code block is then independently executed by all the threads. And you might have guessed it correctly – it’s creating four threads here. Four – because my system has four (logical) cores. There are multiple ways, we can specify the number of threads to be used, but in this case because we haven’t specified it explicitly, it’s automatically(!?) detecting number of cores and accordingly it’s creating threads only for that particular block – and not for full code!
Resources:
- OpenMP website (https://www.openmp.org/)