intMPI_Isend(void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_comm comm, MPI_Request *req) intMPI_Irecv(void *buf, int count, MPI_Datatype datatype, int src, int tag, MPI_Comm comm, MPI_Request *req)
#include<stdio.h> #include<stdlib.h> #include<mpi.h> #include<math.h> intmain(int argc,char **argv) { int myid, numprocs; int tag,source,destination,count; int buffer; MPI_Status status; MPI_Request request; MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD,&numprocs); MPI_Comm_rank(MPI_COMM_WORLD,&myid); tag =2021; /* any integer to tag messages */ source = 0; count = 1; if(myid != source ) { buffer =2077; //其他进程向0号进程发送消息 MPI_Isend(&buffer,count,MPI_INT,source,tag,MPI_COMM_WORLD,&request); MPI_Wait(&request,&status); printf("processor %d send %d to processor %d\n",myid,buffer,source); }
if(myid == source ) { //0号进程接收来自其他进程的消息 for(int i=1;i<numprocs;i++) { MPI_Irecv(&buffer,count,MPI_INT,i,tag,MPI_COMM_WORLD,&request); MPI_Wait(&request,&status); printf("processor %d received %d from processor %d \n",myid,buffer,i); }
}
MPI_Finalize(); return0; }
程序输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
processor 2 send 2077 to processor 0 processor 3 send 2077 to processor 0 processor 5 send 2077 to processor 0 processor 6 send 2077 to processor 0 processor 7 send 2077 to processor 0 processor 8 send 2077 to processor 0 processor 9 send 2077 to processor 0 processor 4 send 2077 to processor 0 processor 1 send 2077 to processor 0 processor 0 received 2077 from processor 1 processor 0 received 2077 from processor 2 processor 0 received 2077 from processor 3 processor 0 received 2077 from processor 4 processor 0 received 2077 from processor 5 processor 0 received 2077 from processor 6 processor 0 received 2077 from processor 7 processor 0 received 2077 from processor 8 processor 0 received 2077 from processor 9