使用 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