使用 OpenMP 并行 hello world
以下 C 代码使用 OpenMP 并行编程模型使用多个线程将线程 ID 和线程数写入 stdout
。
#include <omp.h>
#include <stdio.h>
int main ()
{
#pragma omp parallel
{
// ID of the thread in the current team
int thread_id = omp_get_thread_num();
// Number of threads in the current team
int nthreads = omp_get_num_threads();
printf("I'm thread %d out of %d threads.\n", thread_id, nthreads);
}
return 0;
}
在 Fortran 90+中,等效程序如下所示:
program Hello
use omp_lib, only: omp_get_thread_num, omp_get_num_threads
implicit none
integer::thread_id
integer::nthreads
!$omp parallel private( thread_id, nthreads )
! ID of the thread in the current team
thread_id = omp_get_thread_num()
! Number of threads in the current team
nthreads = omp_get_num_threads()
print *, "I'm thread", thread_id, "out of", nthreads, "threads."
!$omp end parallel
end program Hello