【问题标题】:Problem with MPI_Gatherv for std::vectorstd::vector 的 MPI_Gatherv 问题
【发布时间】:2011-06-29 18:41:31
【问题描述】:

我无法让 MPI_Gatherv 使用 std::vector。我写了一个小程序,应该用 rank+1 的整数填充一个向量(以避免在向量初始化为 0 时为 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

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

感谢您的帮助!

【问题讨论】:

    标签: c++ mpi


    【解决方案1】:

    问题不在于 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);
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-21
      • 2018-05-02
      • 2015-04-08
      • 1970-01-01
      • 2011-01-19
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      相关资源
      最近更新 更多