CS 220 Parallel Computing

blocking.c

DownloadView Raw

/**
 * non-blocking.c
 *
 * Demonstrates blocking communication in MPI: the main process (rank 0) is
 * tasked with incrementing its counter as the program runs. However, the
 * blocking MPI_Recv call will prevent it from doing this work while waiting for
 * a message to be delivered.
 *
 * NOTE: Ranks other than 0 and 1 will be ignored.
 *
 * Compile: mpicc -g -Wall blocking.c -o blocking
 * Run: mpirun -n 2 ./blocking
 */
#include <mpi.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void) {
    MPI_Init(NULL, NULL);

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

    if (rank == 0) {
        int random;
        unsigned long counter = 0;

        while (true) {
            MPI_Recv(&random, 1, MPI_INT, 1, 0,
                    MPI_COMM_WORLD, MPI_STATUS_IGNORE);
            printf("Received number: %d; counter: %lu\n", random, counter);
            counter++;
        }
    } else if (rank == 1) {
        /* I will send a random number to rank 3 after sleeping a random number
         * of seconds */
        int random;
        int sleep_time;
        while (true) {
            random = rand();
            sleep_time = rand() % 3;
            sleep(sleep_time);
            MPI_Send(&random, 1, MPI_INT, 0, 0, MPI_COMM_WORLD);
        }
    }

    MPI_Finalize();
    return 0;
}