0

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
Luke
  • 17
  • 2

1 Answers1

0

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.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • Alright so that fixed the errors so I am no longer getting any errors but it is only going between 0 and 3 – Luke Dec 06 '20 at 00:06
  • @Luke The loop `while (receiver != sender);` is forcing the receiver to be the sender. It should be `while (receiver == sender);`. – MikeCAT Dec 06 '20 at 00:10
  • That was a bad thing on my part....... Now it seems to be working correctly. Thank you! – Luke Dec 06 '20 at 00:18
  • @Luke Also your usage of `srand(time(NULL));` looks wrong. See [c - srand() — why call it only once? - Stack Overflow](https://stackoverflow.com/questions/7343833/srand-why-call-it-only-once). – MikeCAT Dec 06 '20 at 00:24
  • I have it like that because of the sleep function changes the timing so it will pull different values. – Luke Dec 06 '20 at 00:28
  • @Luke but you don't need to re-seed the generator at each iteration of the loop. Just seed it once before that with something like `srand(time(NULL) + rank*137)`. – Hristo Iliev Dec 06 '20 at 15:56