Computing at SLAC
Search SLAC

OpenMP Tutorial

OpenMP's "Hello World"

Name this little "Hello World" program hello.c:
#include <stdio.h>
#include <omp.h>

int main(int argc, char *argv[]) {
  int iam = 0, np = 1;

  #pragma omp parallel default(shared) private(iam, np)
    #if defined (_OPENMP)
      np = omp_get_num_threads();
      iam = omp_get_thread_num();
    printf("Hello from thread %d out of %d\n", iam, np);

Compiling and Linking OpenMP Programs

Once you have your OpenMP example program, you can compile and link it with
  • Linux:
    /afs/ -openmp hello.c -o hello
  • Solaris:
    /afs/slac/package/sunworkshop/10/SUNWspro/bin/cc -xopenmp=noopt hello.c -o hello

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:
alfw@rhel6-64> ./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.


Alf Wachsmann. Last Modified: Mar 01, 2006.