#include #include #include #include int main(int argc, char **argv) { int i, j, p, q, rc; float p_real; int my_rank, cart_rank, source, dest; int ldims[2], coords[2]; int periods[2], reorder; MPI_Comm cart_comm; MPI_Status status; int cval, numvalues; int *values; if ( MPI_Init(&argc, &argv) != MPI_SUCCESS ) exit(-1); if ( MPI_Comm_size(MPI_COMM_WORLD, &p) != MPI_SUCCESS ) exit(-1); if ( MPI_Comm_rank(MPI_COMM_WORLD, &my_rank) != MPI_SUCCESS ) exit(-1); p_real = p; q = sqrt(p_real); if ( q*q != p ) { if ( my_rank == 0 ) printf(" %d**2 != %d: program terminates",q,p); MPI_Finalize(); exit(-1); } if ( (values = (int*)malloc(p*sizeof(int))) == NULL ) { fprintf(stderr,"Failed to allocate values[%d]",p); exit(-1); } /* Create new communicator QxQ dimensions */ ldims[0] = ldims[1] = q; periods[0] = periods[1] = 1; // true reorder = 0; // false if ( MPI_Cart_create(MPI_COMM_WORLD,2,ldims,periods,reorder,&cart_comm) != MPI_SUCCESS ) exit(-1); /* Get process coordinates */ if ( MPI_Comm_rank(cart_comm, &cart_rank) != MPI_SUCCESS ) exit(-1); if ( MPI_Cart_coords(cart_comm, cart_rank, 2, coords) != MPI_SUCCESS ) exit(-1); /* Each process defines a value equal to 2nd coordinate */ cval = coords[0]; numvalues=1; values[0] = values[1] = 0; /* Collectively send value to root process */ if ( MPI_Gather ( &cval, 1, MPI_INTEGER, values, numvalues, MPI_INTEGER, 0, cart_comm ) != MPI_SUCCESS ) exit(-1); if ( cart_rank == 0 ) { printf("Before sending, values = \n"); for (i=0; i < q; i++ ) { for (j=0; j < q; j++ ) { p = i + q*j; printf(" %d",values[p]); } printf("\n"); } } /* Now send value to the process on the right */ if ( MPI_Cart_shift(cart_comm, 0, 1, &source, &dest) != MPI_SUCCESS ) exit(-1); if ( MPI_Sendrecv_replace(&cval, 1, MPI_INTEGER, dest, 0, source, 0, cart_comm, &status) != MPI_SUCCESS ) exit(-1); /* Again, collectively send value to root process */ numvalues=1; if ( MPI_Gather ( &cval, 1, MPI_INTEGER, values, numvalues, MPI_INTEGER, 0, cart_comm ) != MPI_SUCCESS ) exit(-1); if ( cart_rank == 0 ) { printf("After sending, values = \n"); for (i=0; i < q; i++ ) { for (j=0; j < q; j++ ) { p = i + q*j; printf(" %d",values[p]); } printf("\n"); } } ! MPI_Finalize(); return(0); }