MPI_Gather小例子

MPI_Gather的作用:从一组进程中收集数据,汇总到根进程中。
每个进程(包括根进程)将其发送缓冲区中的内容发送到根进程,根进程根据发送这些数据的进程的序列号将它们依次存放到自已的消息缓冲区中.其结果就象一个组中的n个进程(包括根进程在内)都执行了一个调用:

MPI_Send(sendbuf, sendcount, sendtype, root, ...), 

同时根进程执行了n次调用:

MPI_Recv(recvbuf+i*recvcount*extent(recvtype), recvcount, recvtype, i,...)

函数原型:

int MPI_Gather(const void *sendbuf,int sendcount,MPI_Datatype sendtype,void *recvbuf,int recvcount,MPI_Datatype sendtype,int root,MPI_Comm comm)

直接展示结果似乎更为清晰,以下展示一个例子:

rank=0, sbuf[0]=0
rank=0, sbuf[1]=0
rank=0, sbuf[2]=0
rank=1, sbuf[0]=1
rank=1, sbuf[1]=1
rank=1, sbuf[2]=1
rank=2, sbuf[0]=2
rank=2, sbuf[1]=2
rank=2, sbuf[2]=2
after MPI_Gather rbuf value:
rank=0, rbuf[0]=0
rank=0, rbuf[1]=0
rank=0, rbuf[2]=0
rank=0, rbuf[3]=1
rank=0, rbuf[4]=1
rank=0, rbuf[5]=1
rank=0, rbuf[6]=2
rank=0, rbuf[7]=2
rank=0, rbuf[8]=2

下面展示代码示例:

#include "mpi.h"

int main( int argc, char* argv[] ){
    int i;
    int rank, nproc;
    int isend, irecv[32];
 
    MPI_Init( &argc, &argv );
    MPI_Comm_size( MPI_COMM_WORLD, &nproc );
    MPI_Comm_rank( MPI_COMM_WORLD, &rank );

    isend = rank + 1;
	//int MPI_Gather(const void *sendbuf,int sendcount,MPI_Datatype sendtype,void *recvbuf,int recvcount,MPI_Datatype sendtype,int root,MPI_Comm comm)
    MPI_Gather( &isend, 1, MPI_INT, irecv, 1, MPI_INT, 0,
                           MPI_COMM_WORLD);
    if(rank == 0) {
        for(i=0; i<nproc; i++)
            printf("irecv = %d\n", irecv[i]);
        }
    MPI_Finalize();
}

猜你喜欢

转载自blog.csdn.net/zcgyq/article/details/83088162
mpi