c++ - 在 MPI_Reduce 中传递和插入 vector

标签 c++ mpi ms-mpi

我需要缩减节点从其他节点获取元素列表的拷贝(存储在 vector 中)。我定义了自己的还原函数,但它不起作用。程序终止/崩溃。

这是代码:

#include <iostream>
#include "mpi.h"
#include <vector>

using namespace std;

void pushTheElem(vector<int>* in, vector<int>* inout, int *len, MPI_Datatype *datatype)
{
    vector<int>::iterator it;
    for (it = in->begin(); it < in->end(); it++)
    {
        inout->push_back(*it);
    }
}

int main(int argc, char **argv)
{
    int numOfProc, procID;
    vector<int> vect, finalVect;

    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &numOfProc);
    MPI_Comm_rank(MPI_COMM_WORLD, &procID);

    MPI_Op myOp;
    MPI_Op_create((MPI_User_function*)pushTheElem, true, &myOp);

    for (int i = 0; i < 5; i++)
    {
        vect.push_back(procID);
    }

    MPI_Reduce(&vect, &finalVect, 5, MPI_INT, myOp, 0, MPI_COMM_WORLD);

    if (procID == 0)
    {
        vector<int>::iterator it;
        cout << "Final vector elements: " << endl;

        for (it = finalVect.begin(); it < finalVect.end(); it++)
            cout << *it << endl;
    }

    MPI_Finalize();
    return 0;
}

最佳答案

您似乎想从所有进程中收集所有元素。这不是减少,而是收集操作。缩减将多个相同长度的数组合并为一个特定长度的数组:

MPI_Reduce

情况并非如此,当组合两个数组时会产生一个长度等于输入数组之和的数组。使用 MPI,您不能像在缩减操作中那样简单地使用指针进行操作。您不能使用 MPI 发送指针,因为进程具有单独的地址空间。 MPI 接口(interface)确实使用指针,但仅使用包含已知类型和已知大小的数据区域。

您可以使用 MPI_Gather 轻松完成任务。

MPI_Gather

// vect.size() must be the same on every process, otherwise use MPI_Gatherv
// finalVect is only needed on the root.
if (procID == 0) finalVect.resize(numOfProc * vect.size());
MPI_Gather(vect.data(), 5, MPI_INT, finalVect.data(), 5, MPI_INT, 0, MPI_COMM_WORLD);

关于c++ - 在 MPI_Reduce 中传递和插入 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45102240/

相关文章:

c++ - 初始化具有大小的结构 vector 时出错

c++ - MPI 内存分配

c - MPI 标签集

c - 尝试将通信世界拆分为 MPI 中的多个通信世界或 block ?

c++ - 如何在没有 Visual Studio 的情况下在 Windows 上的 cmd 中编译和运行 C/C++ MPI 代码

c++ - 尝试使用方法调用访问方法会引发多个错误

c++ - 缺少 Visual Studio Express 2012 tracker.exe

c++ - 带模板的容器声明

c++ - 混合 openMP/MPI 代码中多线程发送/接收错误