MPI消息传递MPI_Sendrecv的用法
Posted 大雨海棠
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MPI消息传递MPI_Sendrecv的用法相关的知识,希望对你有一定的参考价值。
利用mpi求解微分方程时,经常会遇到不同进程的通讯,特别是如下形式的通讯:
进程0->进程1->进程2->进程3...->进程n->进程0
这时,若单纯的利用MPI_Send, MPI_Recv函数进行通讯的话,容易造成死锁,下面介绍MPI_Sendrecv的来解决这个问题。顾名思义,MPI_Sendrecv表示的作用是将本进程的信息发送出去,并接收其他进程的信息,其调用方式如下:
MPI_Sendrecv( void *sendbuf //initial address of send buffer int sendcount //number of entries to send MPI_Datatype sendtype //type of entries in send buffer int dest //rank of destination int sendtag //send tag void *recvbuf //initial address of receive buffer int recvcount //max number of entries to receive MPI_Datatype recvtype //type of entries in receive buffer int source //rank of source int recvtag //receive tag MPI_Comm comm //group communicator MPI_Status status //return status;
下面给出一个实例:
#include<stdio.h> #include "mpi.h" #include <math.h> #define n 4 int main(int argc, char* argv[]){ int nProcs, Rank, i; double A0[n],A1[n]; MPI_Status status; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nProcs); MPI_Comm_rank(MPI_COMM_WORLD, &Rank); for(int i=0; i<n; i++){ A0[i] = Rank; A1[i] = Rank; } printf("\nBefore exchange A0 A1:\n"); for(i=0;i<n;i++){ printf("rank:%d\t%f\t%f\n",Rank, A0[i], A1[i]); } int rightrank = (Rank + 1) % nProcs; int leftrank = (Rank + nProcs-1)%nProcs; MPI_Barrier(MPI_COMM_WORLD); MPI_Sendrecv(A0, n, MPI_DOUBLE, rightrank,990, A1, n, MPI_DOUBLE, leftrank,990, MPI_COMM_WORLD,&status); MPI_Finalize(); printf("After exchange A0 A1\n"); for(i=0;i<n;i++){ printf("rank:%d %f\t%f\n",Rank, A0[i], A1[i]); } }
下面这条语句表示:将进程为Rank的A0发送到rightrank进程,并接收来自leftrank的A1。
MPI_Sendrecv(A0, n, MPI_DOUBLE, rightrank,990, A1, n, MPI_DOUBLE, leftrank,990, MPI_COMM_WORLD,&status);
得到的数值结果如下:
Before exchange A0 A1 rank:0 0.000000 0.000000 rank:0 0.000000 0.000000 rank:0 0.000000 0.000000 rank:0 0.000000 0.000000 Before exchange A0 A1 rank:1 1.000000 1.000000 rank:1 1.000000 1.000000 rank:1 1.000000 1.000000 rank:1 1.000000 1.000000 Before exchange A0 A1 rank:2 2.000000 2.000000 rank:2 2.000000 2.000000 rank:2 2.000000 2.000000 rank:2 2.000000 2.000000 Before exchange A0 A1 rank:3 3.000000 3.000000 rank:3 3.000000 3.000000 rank:3 3.000000 3.000000 rank:3 3.000000 3.000000 After exchange A0 A1 rank:1 1.000000 0.000000 rank:1 1.000000 0.000000 rank:1 1.000000 0.000000 rank:1 1.000000 0.000000 After exchange A0 A1 rank:2 2.000000 1.000000 rank:2 2.000000 1.000000 rank:2 2.000000 1.000000 rank:2 2.000000 1.000000 After exchange A0 A1 rank:3 3.000000 2.000000 rank:3 3.000000 2.000000 rank:3 3.000000 2.000000 rank:3 3.000000 2.000000 After exchange A0 A1 rank:0 0.000000 3.000000 rank:0 0.000000 3.000000 rank:0 0.000000 3.000000 rank:0 0.000000 3.000000
以上是关于MPI消息传递MPI_Sendrecv的用法的主要内容,如果未能解决你的问题,请参考以下文章
boost mpi:字符串变量在 mpi 消息中传递是不是有最大长度?
#pragma acc host_data use_device 的问题