OpenMP- Hello world!

Lesson 50/71

Hello world!

Let's print the statement "Hello world!" using all the threads. Here the variable tid gives your thread id. Our server has only two threads. Threfore, the Hello world! will be printed twice.

#include <omp.h>
#include <stdio.h>

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

 int nthreads, tid;

 /* Fork a team of threads with each thread having a private tid variable */
 #pragma omp parallel private(tid)
   {

   /* Obtain and print thread id */
   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 terminate */

 }
c++

Input

To compile in your computer this code, run the following:

gcc -o omp_helloc -fopenmp omp_hello.c
$ export OMP_NUM_THREADS=2
$ ./omp_helloc
Hello World from thread = 0
Hello World from thread = 1
Number of threads = 2

Note that the environment variable OMP_NUM_THREADS was used to specify number of threads.

GDPR

When you visit any of our websites, it may store or retrieve information on your browser, mostly in the form of cookies. This information might be about you, your preferences or your device and is mostly used to make the site work as you expect it to. The information does not usually directly identify you, but it can give you a more personalized web experience. Because we respect your right to privacy, you can choose not to allow some types of cookies. Click on the different category headings to find out more and manage your preferences. Please note, that blocking some types of cookies may impact your experience of the site and the services we are able to offer.