Difference between revisions of "OpenMP hello world in C"

From ScientificComputing
Jump to: navigation, search
(openMP Hello World)
Line 71: Line 71:
 
  Hello world from thread 6
 
  Hello world from thread 6
 
  [jarunanp@eu-ms-001-08 test_openmp]$
 
  [jarunanp@eu-ms-001-08 test_openmp]$
 +
 +
* Unset the environment variable OMP_NUM_THREADS
 +
[jarunanp@eu-ms-001-08 test_openmp]$ unset OMP_NUM_THREADS
  
 
* Exit the interactive session
 
* Exit the interactive session

Revision as of 09:29, 14 June 2021

< Examples

Load modules

We will use the new software stack in this tutorial:

[jarunanp@eu-login-11 ~]$ env2lmod  
[jarunanp@eu-login-11 ~]$ module list

Currently Loaded Modules:
  1) StdEnv   2) gcc/4.8.5

openMP Hello World

  • Go to $SCRATCH and create a work directory
 [jarunanp@eu-login-11 ~]$ cd $SCRATCH
 [jarunanp@eu-login-11 jarunanp]$ pwd
 /cluster/scratch/jarunanp
 [jarunanp@eu-login-11 jarunanp]$ mkdir test_openmp
 [jarunanp@eu-login-11 jarunanp]$ cd test_openmp
 [jarunanp@eu-login-11 test_openmp]$ 
  • Create a file named openmp_hello_world.c and edit it with a text editor (vi, nano or emacs)
// OpenMP header
#include <omp.h>
#include <stdio.h>

int main(int argc, char* argv[])
{
    //Parallel region code
    #pragma omp parallel                   
    {
      printf("Hello world from thread %d\n", 
             omp_get_thread_num());
    }  
}
  • Compile the code
[jarunanp@eu-login-11 test_openmp]$ gcc -o openmp_hello_world -fopenmp openmp_hello_world.c
[jarunanp@eu-login-11 test_openmp]$ ll
total 20
-rwxr-x--- 1 user user-group 8680 Jun 14 10:55 openmp_hello_world
-rw-r----- 1 user user-group  231 Jun 14 10:55 openmp_hello_world.c
  • Request an interactive session with a compute node
[jarunanp@eu-login-11 test_openmp]$ bsub -n 4 -Is bash
Generic job.
Job <175495032> is submitted to queue <normal.4h>.
<<Waiting for dispatch ...>>
<<Starting on eu-ms-001-08>>
FILE: /sys/fs/cgroup/cpuset/lsf/euler/job.175495032.32022.1623661994/tasks
[jarunanp@eu-ms-001-08 test_openmp]$ 
  • Execute the code
[jarunanp@eu-ms-001-08 test_openmp]$ export OMP_NUM_THREADS=4
[jarunanp@eu-ms-001-08 test_openmp]$ ./openmp_hello_world
Hello world from thread 1
Hello world from thread 3
Hello world from thread 0
Hello world from thread 2
[jarunanp@eu-ms-001-08 openmp]$ 
[jarunanp@eu-ms-001-08 test_openmp]$ export OMP_NUM_THREADS=8
[jarunanp@eu-ms-001-08 test_openmp]$ ./openmp_hello_world
Hello world from thread 0
Hello world from thread 5
Hello world from thread 3
Hello world from thread 4
Hello world from thread 1
Hello world from thread 7
Hello world from thread 2
Hello world from thread 6
[jarunanp@eu-ms-001-08 test_openmp]$
  • Unset the environment variable OMP_NUM_THREADS
[jarunanp@eu-ms-001-08 test_openmp]$ unset OMP_NUM_THREADS
  • Exit the interactive session
[jarunanp@eu-ms-001-08 test_openmp]$ exit
exit
[jarunanp@eu-login-11 test_openmp]$

< Examples