有时候为了创建2D的拓扑,需要对MPI_COMM_WORLD进行划分。所使用的MPI函数是:
MPI_Comm_split(MPI_Comm comm, int color, int key, MPI_Comm *newcomm)
例子程序(出自MPI Groups, Communicators and Topologies):
#include <stdio.h>
#include <mpi.h>
main (int argc, char **argv)
{
MPI_Comm row_comm, col_comm;
int myrank, size, P=4, Q=3, p, q;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
p = myrank / Q;
q = myrank % Q;
/* Split comm intor row and column comms */
MPI_Comm_split(MPI_COMM_WORLD, p, q, &row_comm);
MPI_Comm_split(MPI_COMM_WORLD, q, p, &col_comm);
int sum, rowsum, colsum;
sum = myrank;
rowsum = myrank;
colsum = myrank;
MPI_Allreduce(MPI_IN_PLACE, &sum, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &rowsum, 1, MPI_INT, MPI_SUM, row_comm);
MPI_Allreduce(MPI_IN_PLACE, &colsum, 1, MPI_INT, MPI_SUM, col_comm);
if (myrank == 0)
printf("The sum of all rank is %d\n", sum);
printf("[%d]: My coordinates are (%d, %d), row sum is %d, col sum is %d\n",myrank,p,q,
rowsum,colsum);
MPI_Finalize();
}
参考资料:
1. http://www.cs.utexas.edu/~pingali/CS378/2011sp/lectures/MPIGroups.ppt