#include "mpi.h"
#include<stdio.h>
int main(int argc,char **argv){
// 每个进程发送100*150矩阵的第rank列的前(100-rank)个数
//stride要>=rcounts[i]
int gsize;
int rank;
int *rbuf,*displs,stride;
int sendarray[100][150],*sptr;
int *rcounts;
int root=0;
MPI_Datatype stype;
stride=102;
for(int i=0;i<100;i++)
for(int j=0;j<150;j++)
sendarray[i][j]=i*150+j;
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&gsize);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
rbuf=(int*)malloc(gsize*stride*sizeof(int));
displs=(int*)malloc(gsize*sizeof(int));
rcounts=(int*)malloc(gsize*sizeof(int));
for(int i=0;i<gsize;i++){
displs[i]=i*stride;
rcounts[i]=100-i;
}
//create the datatype for the column to be sent
MPI_Type_vector(100-rank,1,150,MPI_INT,&stype);
MPI_Type_commit(&stype);
/*sptr is the address of the start of rank column*/
sptr=&sendarray[0][rank];
MPI_Gatherv(sptr,1,stype,rbuf,rcounts,displs,MPI_INT,root,MPI_COMM_WORLD);
if(rank==0){
for(int i=0;i<gsize;i++){
int k=0;
for(int j=displs[i];k<rcounts[i];k++)
printf("%d\n",rbuf[j+k]);
}
}
MPI_Finalize();
}
用MPI_Type_struct的等效实现
MPI_UB type allows the user to easily set the end of the structure
if you define a structure datatype and wish to send or receive multiple items,
you should explicitly include an MPI_UB entry as the last member of the structure
当定义某个结构体,并且需要发送或接收该结构体的多个项时,为了对齐与填充的需要,
需要显示指定MPI_UB的项作为该结构体的最后一个成员
#include "mpi.h"
#include<stdio.h>
int main(int argc,char **argv){
// 每个进程发送100*150矩阵的第rank列的前(100-rank)个数
//stride要>=rcounts[i]
int gsize;
int rank;
int *rbuf,*displs,stride;
int sendarray[100][150],*sptr,disp[2],blocklen[2];
int *rcounts;
int root=0;
MPI_Datatype stype,type[2];
stride=102;
for(int i=0;i<100;i++)
for(int j=0;j<150;j++)
sendarray[i][j]=i*150+j;
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&gsize);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
rbuf=(int*)malloc(gsize*stride*sizeof(int));
displs=(int*)malloc(gsize*sizeof(int));
rcounts=(int*)malloc(gsize*sizeof(int));
for(int i=0;i<gsize;i++){
displs[i]=i*stride;
rcounts[i]=100-i;
}
//create the datatype for one int ,with extent of entire row
blocklen[0]=1,blocklen[1]=1;
disp[0]=0,disp[1]=150*sizeof(int);
type[0]=MPI_INT,type[1]=MPI_UB;
MPI_Type_struct(2,blocklen,disp,type,&stype);
MPI_Type_commit(&stype);
/*sptr is the address of the start of rank column*/
sptr=&sendarray[0][rank];
MPI_Gatherv (sptr,100-rank,stype,rbuf,rcounts,displs,MPI_INT,root,MPI_COMM_WORLD);
if(rank==0){
for(int i=0;i<gsize;i++){
int k=0;
for(int j=displs[i];k<rcounts[i];k++)
printf("%d\n",rbuf[j+k]);
}
}
MPI_Finalize();
}