// ================================================================== // Author: Jean-Michel Richer // Email: jean-michel.richer@univ-angers.fr // Date: Aug 2020 // Last modified: September 2026 // Purpose: Demonstrate basic send functionality, send array of float // from master (rank=0) to slave (rank=1) // ================================================================== // Don't forget to launch with // // mpirun -n 2 bin/ezmpi_send_and_recv.exe // // ================================================================== #include #include // for sleep #include #include #include using namespace std; #include "ezmpi.hpp" using namespace ez::mpi; /** * run master and slaves */ void run(int argc, char* argv[]) { // data to send vector vec; int vec_size; // create process here so that it will be destroyed // at the end of the procedure Process process(argc, argv); process.log(true); if (process.is_master()) { // ---------------------------------------------------------- // Code for the master // ---------------------------------------------------------- // set remote cpu identifier that will communicate with master process.remote(1); vec_size = 10; vec.resize(vec_size); iota(vec.begin(), vec.end(), 1); process << vec << endl; // send vector to slave1 process.send(vec); // wait for slave1 to compute and send back sum float result = 0; process.recv(result); process << "- result is " << result << " for length=" << vec_size; process << ", expected=" << (vec_size * (vec_size + 1)) / 2 << endl; } else if (process.is_slave(1)) { // ---------------------------------------------------------- // Code for the first slave // ---------------------------------------------------------- // tells to Process to send data to master processor process.remote(0); // process of id 1 will receive the vector and compute the sum // we receive the vector process.recv(vec); process << "- receive vector " << vec << endl; // 3- compute sum float sum = std::accumulate(vec.begin(), vec.end(), 0); // 4- send back result process.send(sum); } else { // ---------------------------------------------------------- // Code for the other processes: don't do anything // ---------------------------------------------------------- process << "- is idle" << endl; } process.logs(cout); } /** * main function * */ int main(int argc, char** argv) { srand(time(nullptr)); // call a function that contains the code for the master and // the slaves in order to avoid problems of initialization and // finalization of processes run(argc, argv); exit(EXIT_SUCCESS); }