OpenMP “Hello World”

Hello world!

Let’s print the statement “Hello wordl!” using all the threads in you computer:

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) 
int nthreads, tid;
/* Fork a team of threads giving them their own copies of variables */
#pragma omp parallel private(nthreads, tid)
/* Obtain thread number */
tid = omp_get_thread_num();
printf("Hello World from thread = %d\n", tid);
/* Only master thread does this */
if (tid == 0) 
nthreads = omp_get_num_threads();
printf("Number of threads = %d\n", nthreads);
}  /* All threads join master thread and disband */

Running OpenMP Programs

The OpenMP runtime environment needs an environment variable to tell it how many threads you want to use for your program. In bash syntax, this looks like this


Now you can start your program and it will execute with 4 parallel threads:

$ ./hello
Hello from thread 0 out of 4
Hello from thread 1 out of 4
Hello from thread 2 out of 4
Hello from thread 3 out of 4

Note that if the computer you are executing your OpenMPI program on has fewer CPUs or cores than the number of threads you have specified in OMP_NUM_THREADS, the OpenMP runtime environment will still spawn as many threads but the operating system will sequentialize them.

Last updated by Learn Scientific Programming on August 10, 2017
How did you like this article?0005