MPI figuring out the sender when you recieve message using MPI_STATUS
Andrew Mclaughlin
So I am trying to play hot potato with MPI and I'm having an issue using MPI_STATUS. Here's My Code
MPI_Status status;
if(rank == 0) { printf("Sending %d from %d to %d\n", variable, rank, sender); sleep(3); MPI_Send(&variable, 1, MPI_INT, sender, 0, MPI_COMM_WORLD); } do{ srand(time(NULL)); MPI_Recv(&variable, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status); sender = status.MPI_SOURCE; printf("sender is %s\n", status.MPI_SOURCE); printf("Recieved %d from %d at %d\n", variable, sender, rank); sleep(3); do{ receiver = rand() % world_size; printf("reveiver is %d\n", receiver); } while (receiver != sender);// confirms its not sending it back to the original sender and assuming world_size is greater than 2 printf("Sending %d from %d to %d\n", variable, rank, sender); sleep(3); MPI_Send(&variable, 1, MPI_INT, receiver, 0, MPI_COMM_WORLD); }while (1 == 1);But when I run it what I get is below. I'm not sure what is going wrong.
mpirun -np 4 a.out
Sending 10 from 0 to 3
sender is (null)
Recieved 10 from 0 at 3
reveiver is 1
reveiver is 2
reveiver is 2
reveiver is 3
reveiver is 0
Sending 10 from 3 to 0
[cs2:15514] *** Process received signal ***
[cs2:15514] Signal: Segmentation fault (11)
[cs2:15514] Signal code: Address not mapped (1)
[cs2:15514] Failing at address: 0x3 1 Answer
According to MPI_Status structure - Message Passing Interface | Microsoft Docs
The type of MPI_SOURCE member of the structure MPI_Status is int.
On the other hand, you used %s to print the value in the line
printf("sender is %s\n", status.MPI_SOURCE);This invokes undefined behavior. %s expects data having type char*.
You should use %d instead of that to print the value.