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  (这里数目是按实数的数目,若数据类型为MPI_COMPLEX时,传递的数目要乘以2) 
         int source //rank of source
         int recvtag //receive tag
         MPI_Comm comm //group communicator
         MPI_Status status //return status;

 下面给出一个实例:

#include
#include "mpi.h"
#include 
#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

 下面这条语句表示:将进程为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

  

 

转载于:https://www.cnblogs.com/kuangsyx/p/7903774.html

你可能感兴趣的:(MPI消息传递MPI_Sendrecv的用法)