1

I was wondering if a code like this can cause race conditions or any other error, and in case it can, how should I manage this situation?

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

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

    MPI_Status status;
    MPI_Request req;

    if (!rank) {
        while(condition){
            int recv_buffer;
            int other_recv;
            int value = 1;
            MPI_Recv(&recv_buffer, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
            MPI_Isend(&value, 1, MPI_INT, recv_buffer, status.MPI_SOURCE, MPI_COMM_WORLD, &req);
            MPI_Recv(&other_recv, 1, MPI_INT, status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        }
        /* end signal from process 0 to others */        
    }
    else{
        while(1){
            int buffer = 1;
            int other_value = 1;
            int recv_buffer;

            MPI_Isend(buffer, 1, MPI_INT, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &req);
            MPI_Isend(&other_value, 1, MPI_INT, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &req);
            MPI_Recv(&recv_buffer, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status);
            /* if end message reached => break */
        }
    }
}

I need a communication like this.

Edit:changed some error in code

  • PSA: You don't need to [cast `malloc()` in C](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – tadman May 29 '23 at 18:32
  • Hopefully you `free()` what you allocate here somewhere. You could also use a regular array if you don't need anything fancy. `int recv_buffer[2]` for example. – tadman May 29 '23 at 18:33
  • 1
    It is not the complete code but just the piece where I need to understand if there could be an error – simone russo May 29 '23 at 18:35
  • Fair enough. What's the sequence of events you're expecting to play out here? Maybe if you explain your thinking it'd be easier to verify. – tadman May 29 '23 at 18:36
  • In this code, i expect that the proc 0 receive a message for example first from proc 1 and wait for another message from proc 1 also if, for example, proc 2 already sent a message to it, after received the second message from proc 1, proc 0 can process message from proc 2 and so on – simone russo May 29 '23 at 18:40
  • 5
    You have Undefined Behavior, not a race condition. Start by inserting `MPI_Wait` calls because without those the program is really undefined. – Victor Eijkhout May 29 '23 at 18:51
  • You also need to use an array of 2 requests `MPI_Request reqs[2]` and then `MPI_Waitall(2, reqs, ...)` after the `MPI_Recv()` on non zero ranks – Gilles Gouaillardet May 29 '23 at 21:18

0 Answers0