0
votes

I want to send a MPI_Send message to a single but variable host. By this i mean that i dont know the rank of the host i want to send the message to, at compile time.

So naturally, what i wrote was the following:

MPI_Send(&myIntData, 1, MPI_INT, target_host, MY_MSGTAG, MPI_COMM_WORLD);

where target_host is an integer, containing the rank of the destination.

When i execute this, MPI ends with a timeout. If i put a printf before and after the send, only the printf that happens before is displayed, which means that my program is stuck in the MPI_Send statement.

If i change target_host for a 1, for example, then the second printf displays and everything works fine.

So.. doesnt mpi support a variable in the destintation rank identifier?

What is the problem here?

1
Does target call corresponding MPI_Recv?osgx
Some more code would be useful.user0815

1 Answers

0
votes

MPI does allow for a variable in the rank argument. Consider the following example

#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char** argv){

    int rank = 0;
    int comm_size = 0;

    MPI_Init(&argc, &argv);

    MPI_Comm_size(MPI_COMM_WORLD, &comm_size);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    printf("Rank %d starting\n", rank);
    unsigned int i;

    if(rank == 0){

        for(i = 1; i < comm_size; i++){

            char myString[] = "STRING";
            int len = strlen(myString);
            printf("Sending to %d\n", i);
            MPI_Send(myString, len, MPI_CHAR, i, 0, MPI_COMM_WORLD);

        }
    }
    else{
        char rbuf[4096];            
        MPI_Recv((void*)rbuf, 4096, MPI_CHAR, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        printf("[%d] Got %s in Recv\n", rank, rbuf);
    }


    MPI_Finalize();

}

Compile with mpicc -o my_program example.c and make sure that you run the program with mpiexec -n 2 my_program or a number greater than two for the -n parameter (which is the number of processes to use). In your case, you will need to do a send to rank 0 with the host as the message. Then, in rank 0, you will need a loop to receive from each rank. Something like the following

if(rank != 0){
    MPI_Send(host, host_msg_len, MPI_CHAR, 0, 0, MPI_COMM_WORLD);
}
else{
    for(i = 1; i < comm_size; i++){
        char rbuf[4096];            
        MPI_Recv((void*)rbuf, 4096, MPI_CHAR, i, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);

        if(strcmp(rbuf, target_host) == 0){
            target_rank = i;
            break;
        }
    }
}