2011-02-18 58 views
1

我无法让MPI_Gatherv与std :: vector一起使用。我已经写了一个小程序,应该用一个整数的秩+1来填充一个向量(避免0,因为向量初始化为0)。这只是一个使用2个MPI进程运行的示例程序,我意识到它不具有可扩展性。问题与MPI_Gatherv为std :: vector

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

感谢您的帮助!

回答

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

因为它是,秩为零(在这种情况下是在置换阵列事项的唯一的地方),所有的位移为零,所以一切都被写入数组的开始,并且数组的后半部分未被触及。

相关问题