User Tools

Site Tools


MPI Send and Receive

MPI program using MPI_Send and MPI_Recv for communication between processes.
This program will involve two processes: the master process (rank 0) will send a message to a worker process (rank 1), which will then receive the message and print it.

#include <mpi.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv) {
    // Initialize the MPI environment
    MPI_Init(&argc, &argv);
    // Find out rank, size
    int world_rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
    int world_size;
    MPI_Comm_size(MPI_COMM_WORLD, &world_size);
    // We are assuming at least 2 processes for this task
    if (world_size < 2) {
        fprintf(stderr, "World size must be greater than 1 for %s\n", argv[0]);
        MPI_Abort(MPI_COMM_WORLD, 1);
    int number;
    if (world_rank == 0) {
        // If we are rank 0, set the number to 7 and send it to process 1
        number = 7;
        MPI_Send(&number, 1, MPI_INT, 1, 0, MPI_COMM_WORLD);
        printf("Process 0 sent number %d to process 1\n", number);
    } else if (world_rank == 1) {
        // If we are rank 1, receive the number from process 0
        MPI_Recv(&number, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        printf("Process 1 received number %d from process 0\n", number);
    // Finalize the MPI environment

MPI Initialization: MPI_Init initializes the MPI environment. This must be called before any other MPI functions.

Rank and Size: MPI_Comm_rank gets the rank of the current process, and MPI_Comm_size gets the total number of processes.

Check Number of Processes: We check if the total number of processes is at least 2, as our example requires two processes.

Sending and Receiving:

Master Process (Rank 0): Sets an integer (number) to 7 and sends it to process 1 using MPI_Send. The parameters of MPI_Send include the data to be sent, the count of elements, the datatype, the destination rank, a tag to identify the message, and the communicator.

Worker Process (Rank 1): Receives the integer from process 0 using MPI_Recv. The parameters of MPI_Recv include the buffer to receive the data, the count of elements, the datatype, the source rank, a tag that matches the sent message, the communicator, and a status object (here we use MPI_STATUS_IGNORE as we do not need the status).

Finalization: MPI_Finalize finalizes the MPI environment and should be called when the MPI operations are complete.

To run this program, compile it with an MPI compiler like mpicc and execute it with an MPI execution command like mpirun or mpiexec, specifying at least 2 processes.

c/mpi/send-receive.txt · Last modified: 2024/01/17 10:30 by odefta