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 <omp.h>
#include <iostream>

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::cout << "Hello from main thread of process " << my_rank
      << " of " << process_count << " on " << hostname << std::endl;

    int thread_count = omp_get_max_threads();
    if (argc >= 2) {
      thread_count = atoi(argv[1]);
    }

    #pragma omp parallel num_threads(thread_count)\
      default(none) shared(std::cout, my_rank, process_count, hostname)
    {
      #pragma omp critical(cout)
      std::cout << "   Hello from thread " << omp_get_thread_num()
        << " of " << omp_get_num_threads() << " of process " << my_rank
        << " of " << process_count << " on " << hostname << std::endl;
    }

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