MPI — 1. 基本概念

相关概念与函数

MPI名词:communicator, rank, size
MPI函数:MPI_Comm_rank, MPI_Comm_size, MPI_Init, MPI_Finalize

  • 如何理解MPI概念中的 communicator

为完成某个并行计算的所涉及的进程合在一起的进程组称之为communicator, 会有一个“名字”可以区分,知道这个名字也可以知道这个组下面有哪些进程。这个是我自己总结的,可能不准确。下面是官方ppt中解释:
MPI processes can be collected into groups
--Each group can have multiple colors(some times called context)
--Group + color == communicator(it is like)
--The same group can have many names, but simple programs do not have to worry about multiple names
一个communicator会有多个名字,这个不知有何作用,日后有时间再研究

  • rank,size

当知道了一个communicator后,会有rank,size这两个概念。size用于表示当前communicator中进程的数量,rank用于标识具体哪个进程,是用以int变量来表示的。这两个变量取值,分别通过MPI_Comm_rank(), MPI_Comm_size()来获取的。在MPI编程首先要是使用MPI_Init()函数来初始化,编程结束要用MPI_Finalize()来结束MPI进程,否则会产生异常。

查看MPICH中头文件'mpi.h', MPI_Comm_rank(), MPI_Comm_size()的定义如下:

MPI_Comm_rank(MPI_Comm comm, int *rank);
MPI_Comm_size(MPI_Comm comm, int *size);

其中MPI_Comm是MPI实现中communicator的类型定义,实际上是一个int类型。mpi.h是这样定义的:

typedef int MPI_Comm

下面代码中,MPI_COMM_WORLD是默认通信组,用来初始化MPI通信组名。

#define MPI_COMM_WORLD ((MPI_Comm)0x44000000)
int rank, size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);

写一个简单的hello world代码,在各个进程中打印“hello world”

#include<mpi.h>
#include<iostream>
using namespace std;

int main(int argc, char** argv) {
    int rank, size;
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    cout << "Hello World. I am " << rank << " of " << size << endl;
    MPI_Finalize();
    return 0;
}

运行结果如下:

mpicxx hello.cpp -o hello
mpiexec -np 3 ./hello

Hello World. I am 0 of 3
Hello World. I am 1 of 3
Hello World. I am 2 of 3

posted @ 2021-08-15 17:56  星辰大海,绿色星球  阅读(1053)  评论(0编辑  收藏  举报