📜  MPI_Sendrecv - C++ (1)

📅  最后修改于: 2023-12-03 14:44:24.513000             🧑  作者: Mango

MPI_Sendrecv - C++

MPI_Sendrecv is a function in the MPI library that allows the sending and receiving of messages between processes in parallel computing. It is a blocking function, which means that the program execution will halt until the message is sent and received successfully.

Syntax

The syntax for MPI_Sendrecv in C++ is as follows:

MPI_Sendrecv(void *sendbuf, int sendcount, MPI_Datatype sendtype, int dest, int sendtag, void *recvbuf, int recvcount, MPI_Datatype recvtype, int source, int recvtag, MPI_Comm comm, MPI_Status *status)
Parameters
  • sendbuf - The starting address of the send buffer.
  • sendcount - The number of elements in the send buffer.
  • sendtype - The datatype of each element in the send buffer.
  • dest - The rank of the destination process in the communicator.
  • sendtag - The tag for the message being sent.
  • recvbuf - The starting address of the receive buffer.
  • recvcount - The number of elements in the receive buffer.
  • recvtype - The datatype of each element in the receive buffer.
  • source - The rank of the source process in the communicator.
  • recvtag - The tag for the message being received.
  • comm - The communicator to use for communication.
  • status - The status of the message being sent and received.
Example

Here is an example of using MPI_Sendrecv in C++ to send a message from process 0 to process 1:

#include <mpi.h>
#include <iostream>
 
int main(int argc, char **argv)
{
    int rank, size;
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
 
    int sendbuf = 123;
    int recvbuf = 0;
    MPI_Status status;
 
    if (rank == 0)
    {
        MPI_Sendrecv(&sendbuf, 1, MPI_INT, 1, 0, &recvbuf, 1, MPI_INT, 1, 1, MPI_COMM_WORLD, &status);
        std::cout << "Process " << rank << " sent " << sendbuf << " and received " << recvbuf << std::endl;
    }
    else if (rank == 1)
    {
        MPI_Sendrecv(&sendbuf, 1, MPI_INT, 0, 1, &recvbuf, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, &status);
        std::cout << "Process " << rank << " sent " << sendbuf << " and received " << recvbuf << std::endl;
    }
 
    MPI_Finalize();
    return 0;
}

This program initializes MPI and gets the rank of the current process and the size of the communicator. Next, process 0 sends the integer value 123 to process 1 using MPI_Sendrecv, which sends the message and waits for the response. Process 1 receives the message and sends a response using the same function. Finally, both processes print out the messages they sent and received.

Conclusion

MPI_Sendrecv is a useful function in the MPI library for parallel computing, allowing for the sending and receiving of messages between processes. It is important to note that this is a blocking function, meaning that program execution will halt until the message is sent and received.