Jump to content

MPI: Send & Recv

From Haidhi Wiki
Revision as of 07:07, 13 March 2026 by SanzSkuy (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

MPI_Send dan MPI_Recv ada "point-to-point" function untuk komunikasi antar proses.

#include <mpi.h>
#include <iostream>

int main(int argc, char** argv) {
    MPI_Init(NULL, NULL);

    int world_rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
    int world_size;
    MPI_Comm_size(MPI_COMM_WORLD, &world_size);

    if (world_size < 2) {
        printf("Minimum 2 processes required\n");
        MPI_Abort(MPI_COMM_WORLD, 1);
    }

    int number;
    if (world_rank == 0) {
        number = 777;
        MPI_Send(
            &number,        // data
            1,              // count
            MPI_INT,        // datatype
            1,              // destination
            0,              // tag
            MPI_COMM_WORLD  // communicator
        );
        printf("Process 0 send number %d to Process 1\n", number);

    } else if (world_rank == 1) {
        MPI_Recv(
            &number,        // data
            1,              // count
            MPI_INT,        // datatype
            0,              // source
            0,              // tag
            MPI_COMM_WORLD, // communicator
            MPI_STATUS_IGNORE
        );
        printf("Process 1 succesfully retrieve number %d from Process 0!\n", number);
    }

    MPI_Finalize();
    return 0;
}