对于std :: vector的MPI_Gatherv有问题 [英] Problem with MPI_Gatherv for std::vector

查看:101
本文介绍了对于std :: vector的MPI_Gatherv有问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having trouble getting MPI_Gatherv to work with a std::vector. I have written a small program that should fill a vector with integers of rank+1 (to avoid 0 as the vector is initialized to 0s). This is just an example program to run with 2 MPI processes, I realize that it is not very scalable.

#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的理解失败吗?

So for some reason it only inserts process 1's integers in the first half of the vector. Does anyone have any idea what's going on here? I have also tried implementing it with a normal C style array and I get the same result. But if I write it in C instead of C++ it works. Is this a failing in my understanding of C++ and MPI?

感谢您的帮助!

推荐答案

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

The issue isn't with std::vector; there's just a typo in your code calculating the displacements. This:

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);
}

就像这样,对于秩0其中位移数组很重要),所有位移都为零,所以一切都被写入数组的开始,而数组的第二半是未触及的。

As it was, for rank zero (which in this case is the only place where the displacement array matters), all the displacements were zero, so everything was getting written to the start of the array, and the second half of the array was untouched.

这篇关于对于std :: vector的MPI_Gatherv有问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆