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 <iostream>
#include <cstdint>
#include <vector>

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);

    std::vector<int64_t> numbers;

    if (my_rank == 0) {
      int64_t number = 0;
      while (std::cin >> number) {
        numbers.push_back(number);
      }

      size_t number_count = numbers.size();
      for (int dest = 1; dest < process_count; ++dest) {
        MPI_Send(&number_count, /*count*/ 1, MPI_UINT64_T, dest, /*tag*/ 0
          , MPI_COMM_WORLD);
        MPI_Send(&numbers[0], number_count, MPI_INT64_T, dest, /*tag*/ 0
          , MPI_COMM_WORLD);
      }
    }
    else {
      size_t number_count = numbers.size();
      MPI_Recv(&number_count, /*capacity*/ 1, MPI_UINT64_T
        , /*source*/ 0, /*tag*/ 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
      numbers.resize(number_count);
      MPI_Recv(&numbers[0], /*capacity*/ number_count, MPI_INT64_T
        , 0, /*tag*/ 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    }

    if (numbers.size() > 1) {
      std::cout << "Process " << my_rank << " has " << numbers[0] << std::endl;
    }

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