Rookie HPC

About

Docs

Tools

Tests

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 buffers used for send and receive must be different.

Copy

Feedback

int MPI_Sendrecv(const void* buffer_send,
                 int count_send,
                 MPI_Datatype datatype_send,
                 int recipient,
                 int tag_send,
                 void* buffer_receive,
                 int count_receive,
                 MPI_Datatype datatype_receive,
                 int sender,
                 int tag_receive,
                 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 apply to the send message.
buffer_receive
The buffer in which receive the message.
count_receive
The number of elements to receive.
datatype_receive
The type of one receive buffer element.
sender
The rank of the sender MPI process. If there is no restriction on the sender’s rank, MPI_ANY_SOURCE can be passed.
tag_receive
The tag to require from the message. If no tag is required, MPI_ANY_TAG can be passed.
communicator
The communicator in which the communications take place.
status
The variable in which store the reception status returned. If it is not needed, MPI_STATUS_IGNORE can be passed.

Returned value

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 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;
}