MPI学习(三)-通过OpenmMP使用MPI

MPI-通过OpenMP使用MPI

OpenMP是另一种为基于共享内存的并行编程提供的应用编程接口。当人们想使用多核处理器时,通常使用OpenMP。下面是一个“Hello World”程序,使用了MPI和OpenMP的API。

程序运行平台

北京超级云计算中心A3分区

环境变量

mpi/intel/2017.5

编译指令

mpic++ -fopenmp mpi003.cpp -o mpi003

运行指令

srun -p amd_256 -N 2 -n 2 ./mpi003(使用SLURM任务调度系统)

2个分区,核数为2

程序源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <math.h>
#include <omp.h> //OpenMP所需要的头文件
#include <mpi.h>
int main(int argc,char **argv)
{
int myid, numprocs;
int namelen;
int thread_id , nthreads;
char processor_name[MPI_MAX_PROCESSOR_NAME];
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
MPI_Get_processor_name(processor_name, &namelen);
//构造并行区
#pragma omp parallel private(thread_id, nthreads) num_threads(8) //设置线程数为8
{
thread_id = omp_get_thread_num(); //获得当前线程的id
nthreads = omp_get_num_threads(); //获得总的线程数
printf("Thread number %d (on %d) for the MPI process number %d (on %d) [%s]\n",
thread_id, nthreads, myid, numprocs, processor_name);
}
MPI_Finalize();
return 0;
}

程序运行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Thread number 0 (on 8) for the MPI process number 1 (on 2) [eb1316.para.bscc]
Thread number 4 (on 8) for the MPI process number 1 (on 2) [eb1316.para.bscc]
Thread number 3 (on 8) for the MPI process number 1 (on 2) [eb1316.para.bscc]
Thread number 5 (on 8) for the MPI process number 1 (on 2) [eb1316.para.bscc]
Thread number 2 (on 8) for the MPI process number 1 (on 2) [eb1316.para.bscc]
Thread number 6 (on 8) for the MPI process number 1 (on 2) [eb1316.para.bscc]
Thread number 0 (on 8) for the MPI process number 0 (on 2) [eb1314.para.bscc]
Thread number 1 (on 8) for the MPI process number 0 (on 2) [eb1314.para.bscc]
Thread number 2 (on 8) for the MPI process number 0 (on 2) [eb1314.para.bscc]
Thread number 5 (on 8) for the MPI process number 0 (on 2) [eb1314.para.bscc]
Thread number 1 (on 8) for the MPI process number 1 (on 2) [eb1316.para.bscc]
Thread number 7 (on 8) for the MPI process number 1 (on 2) [eb1316.para.bscc]
Thread number 3 (on 8) for the MPI process number 0 (on 2) [eb1314.para.bscc]
Thread number 4 (on 8) for the MPI process number 0 (on 2) [eb1314.para.bscc]
Thread number 6 (on 8) for the MPI process number 0 (on 2) [eb1314.para.bscc]
Thread number 7 (on 8) for the MPI process number 0 (on 2) [eb1314.para.bscc]