I’m trying to send from process with rank = 0 to all other process (1,2,3,4) a value from the vector n_pointsBuffer. The problem is that just process 0 gets its value but the others don’t. Can anyone explain to me if it’s possible what I’m trying to do, if so, how? It’s the first time I use MPI.
#include <mpi.h>
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int main(int argc, char* argv[]) {
MPI::Init(argc, argv);
int num_procs = MPI::COMM_WORLD.Get_size();
int rank = MPI::COMM_WORLD.Get_rank();
srand(getpid());
int n_points;
if (rank == 0) {
int n_pointsBuffer[] = { 1000000, 1203100, 1231230, 1231000, 1312322 };
MPI::COMM_WORLD.Scatter(n_pointsBuffer, 1, MPI::INT, &n_points, 1,
MPI::INT, 0);
}
cout << "Rank = " << rank << ", n_points = " << n_points << "\n";
double sum = 0;
for (int i = 0; i < n_points; i++) {
double x = rand() / ((double) (RAND_MAX));
double f = 1.0 / (1.0 + x * x);
sum += f;
}
double avg_sum = 0;
MPI::COMM_WORLD.Reduce(&sum, &avg_sum, 1, MPI::DOUBLE, MPI::SUM, 0);
if (rank == 0) {
double pi = 4.0 * (avg_sum / num_procs / ((double) (n_points)));
cout << "Pi is approx " << pi << " with error " << pi - M_PI << ".\n";
}
MPI::Finalize();
return 0;
}
This is because everyone has to call
Scatter(). Not just the root. Quoting from another Answer :Please note that the same holds for every collective operation. An example of using Broadcast is here (You can also find some other programs in the same repo, these were written by me to test my MPI cluster made of dumped machines) .