将矢量分散到变量MPI中

BRa*_*t27 1 c++ scatter mpi

我正在尝试从rank = 0的进程发送到所有其他进程(1,2,3,4)来自向量的值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;
}
Run Code Online (Sandbox Code Playgroud)

axi*_*iom 6

这是因为每个人都必须打电话Scatter().不只是根.引用另一个答案:

MPI_Scatter函数包含发送和接收逻辑.根进程(此处指定为0)发送数据,并且所有接收者都接收到; 参与的每个人都必须打电话给例程.Scatter是MPI集体操作的一个示例,其中通信器中的所有任务都必须调用相同的例程.广播,屏障,减少操作和收集操作是其他示例.

请注意,每次集体操作都是如此.这里使用Broadcast的一个例子(您也可以在同一个repo中找到一些其他程序,这些程序是我编写的,用于测试由倾卸机器组成的MPI集群).