Sending

C | Fortran-2008 | Fortran-90

MPI_Sendrecv

Definition

MPI_Sendrecv 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_replace is that with MPI_Sendrecv the buffers used for send and receive must be different. This allows for instance MPI_Sendrecv to send and receive different amounts and types of data.

Copy

Feedback

int MPI_Sendrecv(const void* buffer_send,
                 int count_send,
                 MPI_Datatype datatype_send,
                 int recipient,
                 int tag_send,
                 void* buffer_recv,
                 int count_recv,
                 MPI_Datatype datatype_recv,
                 int sender,
                 int tag_recv,
                 MPI_Comm communicator,
                 MPI_Status* status);

Parameters

buffer_send

The buffer to send.

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.

buffer_recv

The buffer in which receive the message.

count_recv

The number of elements to receive.

datatype_recv

The type of one receive buffer element.

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.

Return value

The error code returned from the send receive.

Example

Copy

Feedback

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

/**
 * @brief Pair communications between 2 MPI processes sending a message to each other.
 **/
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_send = (my_rank == 0) ? 12345 : 67890;
    int buffer_recv;
    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_send, peer);
    MPI_Sendrecv(&buffer_send, 1, MPI_INT, peer, tag_send,
                 &buffer_recv, 1, MPI_INT, peer, tag_recv, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    printf("MPI process %d received value %d from MPI process %d.\n", my_rank, buffer_recv, peer);

    MPI_Finalize();

    return EXIT_SUCCESS;
}