CS 220 Parallel Computing

hello_send.c

DownloadView Raw

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

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

    /* Total number of processes in this MPI communicator */
    int comm_sz;
    MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);

    /* Get the rank of this process */
    int rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    /* Hostname */
    char hostname[MPI_MAX_PROCESSOR_NAME];
    int name_sz;
    MPI_Get_processor_name(hostname, &name_sz);


    if (rank == 0) {
        /* Leader */
        int i;
        for (i = 1; i < comm_sz; ++i) {
            char buffer[1000];
            MPI_Recv(buffer, 1000, MPI_CHAR, i, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
            printf("Printing at Rank 0: %s\n", buffer);
        }
    } else {
        /* Followers */
        char buffer[1000];
        sprintf(buffer, "Hello world from %d\n", rank);
        MPI_Send(buffer, 1000, MPI_CHAR, 0, 0, MPI_COMM_WORLD);
    }


    /* Clean up */
    MPI_Finalize();
    return 0;
}