Rookie HPC

Sending

C | FORTRAN | FORTRAN-2008

MPI_Sendrecv_replace

Definition

MPI_Sendrecv_replace is a combination of an MPI_Send and an MPI_Recv. It can be seen as having both subroutines executed concurrently. The difference with MPI_Sendrecv is that MPI_Sendrecv_replace uses the same buffer for sending and receiving. This also implies that the amount and type of data sent and received are identical.

Copy

Feedback

int MPI_Sendrecv_replace(const void* buffer,
                         int count_send,
                         MPI_Datatype datatype_send,
                         int recipient,
                         int tag_send,
                         int sender,
                         int tag_recv,
                         MPI_Comm communicator,
                         MPI_Status* status);

Parameters

buffer
The buffer to send, as well as the buffer in which then receive the data.
count_send
The number of elements to send.
datatype_send
The type of one send buffer element.
recipient
The rank of the recipient MPI process.
tag_send
The tag to assign to the send message.
sender
The rank of the sender MPI process.
tag_recv
The tag to require from the message. If no tag is required, MPI_ANY_TAG can be passed.
communicator
The communicator in which the send receive takes place.
status
The variable in which store the reception status returned. If it is not needed, MPI_STATUS_IGNORE can be passed.

Returned value

The error code returned from the send receive.

MPI_SUCCESS
The routine successfully completed.

Example

Copy

Feedback

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

/**
 * @brief Pair communications between 2 MPI processes exchanging an integer.
 **/
int main(int argc, char* argv[])
{
    MPI_Init(&argc, &argv);

    // Make sure exactly 2 MPI processes are used
    int size;
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    if(size != 2)
    {
        printf("%d MPI processes used, please use 2.\n", size);
        MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
    }

    // Prepare parameters
    int my_rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
    int buffer = (my_rank == 0) ? 12345 : 67890;
    int tag_send = 0;
    int tag_recv = tag_send;
    int peer = (my_rank == 0) ? 1 : 0;

    // Issue the send + receive at the same time
    printf("MPI process %d sends value %d to MPI process %d.\n", my_rank, buffer, peer);
    MPI_Sendrecv_replace(&buffer, 1, MPI_INT, peer, tag_send, peer, tag_recv, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    printf("MPI process %d received value %d from MPI process %d.\n", my_rank, buffer, peer);

    MPI_Finalize();

    return EXIT_SUCCESS;
}