c++ - std::vector 的 MPI_Gatherv 问题

标签 c++ mpi

我无法让 MPI_Gatherv 使用 std::vector。我写了一个小程序,应该用 rank+1 的整数填充一个 vector (以避免 0,因为 vector 被初始化为 0)。这只是一个使用 2 个 MPI 进程运行的示例程序,我意识到它的可扩展性不是很好。

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


int main(int argc, char **argv)
{
    int my_rank;    //rank of process
    int p;          //number of MPI processes
    int tag=50;     //Tag for message

    int X = 32;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
    MPI_Comm_size(MPI_COMM_WORLD, &p);

    std::vector<int> rcvvec(X);
    std::vector<int> sndvec(X/p);

    int rcounts[p];
    int rdisp[p];

    for(int i=0; i<p; ++i) {
            rcounts[i] = X/p;
            rdisp[i] = my_rank*(X/p);
    }

    for (int i = 0; i < X/p; ++i)
            sndvec[i] = my_rank+1;

    MPI_Gatherv(&sndvec.front(), rcounts[my_rank], MPI_INT, &rcvvec.front(), rcounts, rdisp, MPI_INT, 0, MPI_COMM_WORLD);

    if (!my_rank) {
            for (int i = 0; i < rcvvec.size(); ++i) {
                    std::cout<<rcvvec[i]<<" ";
            } std::cout<<std::endl;
    }

    MPI_Finalize();
}

我希望 rcvvec 包含 1111111122222222

但我得到的是 2222222200000000

所以出于某种原因,它只在 vector 的前半部分插入进程 1 的整数。有谁知道这里发生了什么?我也尝试过用普通的 C 样式数组实现它,我得到了相同的结果。但如果我用 C 而不是 C++ 编写它,它就可以工作。这是我对 C++ 和 MPI 的理解失败吗?

感谢您的帮助!

最佳答案

问题不在于 std::vector;计算位移的代码中只有一个错字。这:

for(int i=0; i<p; ++i) {
        rcounts[i] = X/p;
        rdisp[i] = my_rank*(X/p);
}

应该是这样的:

for(int i=0; i<p; ++i) {
        rcounts[i] = X/p;
        rdisp[i] = i*(X/p);
}

事实上,对于零阶(在这种情况下,这是位移数组唯一重要的地方),所有位移都是零,所以所有内容都被写入数组的开头,而后半部分阵列未受影响。

关于c++ - std::vector 的 MPI_Gatherv 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5040879/

相关文章:

c - MPI 发送和接收不适用于超过 8182 双

c++ - Visual Studio 中的 CMake 项目 : How to add additional include and library directories?

C++ cin.fail() 问题

c++ - 区分用户类型和原语

c++ - 如何找到 MPI 消息截断错误的来源?

mpi - 并行计算中处理器和进程的区别?

multiprocessing - MPI 未使用分配的所有 CPU

字符串比较中的C++字符

c++ - 如何使用 GLSL 在体积渲染中进行混合?

c++ - MPI_ERR_TRUNCATE : On Broadcast