我正在尝试从 rank = 0 的进程向所有其他进程 (1,2,3,4) 发送来自 vector 的值n_pointsBuffer
。问题是只有进程 0 得到它的值,而其他进程没有。任何人都可以向我解释我是否可以尝试做什么,如果可以,怎么做?这是我第一次使用 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;
}