Receiving

C | Fortran-2008 | Fortran-90

MPI_Recv

Definition

MPI_Recv receives a message in a blocking fashion: it will block until completion, which is reached when the incoming message is copied to the buffer given. Its non-blocking counterpart is MPI_Irecv.

Copy

Feedback

int MPI_Recv(void* buffer,
             int count,
             MPI_Datatype datatype,
             int sender,
             int tag,
             MPI_Comm communicator,
             MPI_Status* status);

Parameters

buffer

The buffer in which receive the message.

count

The number of elements in the buffer given. The number of elements in the message to receive must therefore be less than or equal to that value.

datatype

The type of one 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

The tag to require from the message. If no tag is required, MPI_ANY_TAG can be passed.

communicator

The communicator in which the communication takes place.

status

The variable in which store the status of the receive operation. Pass MPI_STATUS_IGNORE if unused.

Return value

The error code returned from the receive.

Example

Copy

Feedback

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

/**
 * @brief Illustrates how to receive a message in a synchronous fashion.
 * @details This program is meant to be run with 2 processes: a sender and a
 * receiver.
 **/
int main(int argc, char* argv[])
{
    MPI_Init(&argc, &argv);

    // Get the number of processes and check only 2 processes are used
    int size;
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    if(size != 2)
    {
        printf("This application is meant to be run with 2 processes.\n");
        MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
    }

    // Get my rank and do the corresponding job
    enum role_ranks { SENDER, RECEIVER };
    int my_rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
    switch(my_rank)
    {
        case SENDER:
        {
            // The "master" MPI process issues the MPI_Ssend.
            int buffer_sent = 12345;
            printf("MPI process %d sends value %d.\n", my_rank, buffer_sent);
            MPI_Ssend(&buffer_sent, 1, MPI_INT, RECEIVER, 0, MPI_COMM_WORLD);
            break;
        }
        case RECEIVER:
        {
            // The "slave" MPI process receives the message.
            int received;
            MPI_Recv(&received, 1, MPI_INT, SENDER, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
            printf("MPI process %d received value: %d.\n", my_rank, received);
            break;
        }
    }

    MPI_Finalize();

    return EXIT_SUCCESS;
}