Download cpp source code

/*
 * Copyright 2021 Jeisson Hidalgo-Cespedes - Universidad de Costa Rica
 * Creates a secondary thread that greets in the standard output
 */

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

int random(std::mt19937& randomEngine, int min, int max) {
  // Produce random values with uniform discrete distribution
  std::uniform_int_distribution<int> randomDistribution(min, max - 1);
  // Generate and return a random number using the uniform distribution
  return randomDistribution(randomEngine);
}

int main(int argc, char* argv[]) {
  if (MPI_Init(&argc, &argv) == MPI_SUCCESS) {
    int my_rank = -1;
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);

    int process_count = -1;
    MPI_Comm_size(MPI_COMM_WORLD, &process_count);

    char hostname[MPI_MAX_PROCESSOR_NAME];
    int hostname_len = -1;
    MPI_Get_processor_name(hostname, &hostname_len);

    // Try to get a seed from hardware, if available
    std::random_device::result_type seed = std::random_device()();
    // This object generates randon numbers using the Mersenne-Twister algoritym
    std::mt19937 randomEngine(seed + my_rank);

    // srand(MPI_Wtime() * 1e9 + my_rank);
    int my_lucky_number = random(randomEngine, 0, 100);

    const int32_t previous = (process_count + my_rank - 1) % process_count;
    const int32_t next = (my_rank + 1) % process_count;
    int32_t can_print = 1;

    if (my_rank != 0) {
      MPI_Recv(&can_print, /*capacity*/ 1, MPI_INT32_T, /*source*/previous
        , /*tag*/ 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    }

    std::cout << "Process " << my_rank << "/" << process_count
      << ": my lucky number is " << my_lucky_number << std::endl;

    if (my_rank < process_count - 1) {
      MPI_Send(&can_print, /*count*/ 1, MPI_INT32_T, /*dest*/ next, /*tag*/ 0
        , MPI_COMM_WORLD);
    }

    int global_min = -1;
    int global_sum = -1;
    int global_max = -1;

    MPI_Reduce(&my_lucky_number, &global_min, /*count*/ 1,
               MPI_INT, MPI_MIN, /*root*/ 0, MPI_COMM_WORLD);
    MPI_Reduce(&my_lucky_number, &global_sum, /*count*/ 1,
               MPI_INT, MPI_SUM, /*root*/ 0, MPI_COMM_WORLD);
    MPI_Reduce(&my_lucky_number, &global_max, /*count*/ 1,
               MPI_INT, MPI_MAX, /*root*/ 0, MPI_COMM_WORLD);

    if (my_rank == 0) {
      std::cout << "Process " << my_rank << "/" << process_count
        << ": all minimum " << global_min << std::endl;

      const double average = double(global_sum) / process_count;
      std::cout << "Process " << my_rank << "/" << process_count
        << ": all average " << average << std::endl;

      std::cout << "Process " << my_rank << "/" << process_count
        << ": all maximum " << global_max << std::endl;
    }

    MPI_Finalize();
  } else {
    std::cout << "Error: could not init MPI environment" << std::endl;
  }
  return 0;
}