Home > Back-end >  Send to a negative MPI rank destination
Send to a negative MPI rank destination

Time:06-25

I was wondering what happens whenever i specify a negative rank as a destination while sending or a negative rank as a source when receiving. This can happen when using MPI_Cart. In most definitions it only states "Ranks must be between zero and the size of the communicator minus one" Mpich documentation. Thus I wonder whether I need to safeguard against this or whether this is bad style to not block this explicitly from happening. Is writing code like this safe and good practice?

#include <stdio.h>
#include <mpi.h>

int main(int argc, char **argv) {
    int size, rank;

    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    fprintf(stdout, "Size: %i Rank: %i\n", size, rank);

    int a = 10;

    if (rank == 0){
        a  ;
        MPI_Send(
                &a,
                1,
                MPI_INT,
                -2,
                0,
                MPI_COMM_WORLD
        );
    }

    if (rank == 1){
        MPI_Recv(
                &a,
                1,
                MPI_INT,
                -2,
                0,
                MPI_COMM_WORLD,
                MPI_STATUS_IGNORE
        );
    }

    MPI_Barrier(MPI_COMM_WORLD);

    fprintf(stdout, "Size: %i Rank: %i a: %i\n", size, rank, a);

    MPI_Finalize();

    return 0;
}

CodePudding user response:

The variable MPI_PROC_NULL is usually defined as -1 or -2, and sending to the null proc always succeeds. Ditto receiving: your receive buffer will remain unchanged. Sending to other negative values will probably give an error about "invalid rank". However, it's dangerous to rely on the explicit values because it can be installation dependent.

You should test for MPI_PROC_NULL and skip those operations. In fact, I suspect that your Cartesian routines are defined as giving you that value, rather than explicitly -1. Also, Cartesian routines may state "thou shalt not use coordinates outside the grid" and doing do is probably undefined behavior.

  •  Tags:  
  • c mpi
  • Related