Example of openMP

Can you give an example of a basic openmp program?

I want to to spawn multiple threads from a loop, have each thread determine which CPU its running on, and determine how many times each thread was run on each processor.

  • Thanks

Hi,

Below is a simple openMP program that spawns two threads. Each thread prints its process ID (using the getpid() function), loop index variable, and thread number (using the omp_get_thread_num() function).


       program ompdemo

        integer omp_get_thread_num
        integer getpid

        call omp_set_num_threads(2)

!$omp parallel

        do i=1,2
                write (*,*) 'hello world ', getpid(), omp_get_thread_num(), i
        enddo

!$omp end parallel

        end

To compile the above program:

pgf90 -mp omp.F

or

pgf77 -mp omp.F

Below is a sample output:

 hello world        21765           0           1
 hello world        21765           0           2
 hello world        21767           1           1
 hello world        21767           1           2

Now to address your other points. There is no real way to determine which CPU is executing an OpenMP thread. Even if you could determing the physical CPU, the thread could get dispatched by the OS on any CPU at any instance of program execution. On the other hand, if you were to use a hybrid MPI/OpenMP program, you could determine a thread’s process number (rank). The example code below is demonstrates this. To try out the following program, you’ll need the PGI CDK:

       program hybrid

        include 'mpif.h'

        integer omp_get_thread_num
        integer getpid
        integer ierror, rank

        call MPI_INIT(ierror)
        call MPI_COMM_RANK(MPI_COMM_WORLD, rank, ierror)

        call omp_set_num_threads(2)

!$omp parallel

        do i=1,2
                write (*,*) 'hello world ', getpid(), omp_get_thread_num(), i, rank
        enddo

!$omp end parallel

        call MPI_FINALIZE(ierror)

        end

To compile (using the CDK):

pgf90 -Mmpi -mp ompmpi.F

or

pgf77 -Mmpi -mp ompmpi.F

To run with 2 processes:

mpirun -np 2 a.out

Sample output:

 hello world        22508           0           1           0
 hello world        22508           0           2           0
 hello world        22525           1           1           0
 hello world        22525           1           2           0
 hello world        22520           0           1           1
 hello world        22520           0           2           1
 hello world        22524           1           1           1
 hello world        22524           1           2           1

Each process has two threads. The last column in the above output is the rank or process number. When the processes are spawned on distributed nodes, you can consider rank as a CPU number. You can also use a call to gethostname() to verify that the threads/processes are going to the expected nodes.


-Mark