2016-06-12 89 views
0

我试图在主从之间来回发送std::list<int>。但我不确定如何创建MPI数据类型并将列表传递给从机。我想这样做,而不使用另一个库,如boost。我正在努力解决这个post,但我无法与list一起工作。以下是我正在使用的代码。使用C++ OpenMPI发送和接收主从进程之间的列表

#include <iostream> 
#include <list> 
#include "mpi.h" 
#include <stdio.h> 
#include <stdlib.h> 

using namespace std; 

int main(int argc, char **argv) 
{ 
int rank, size, tag, rc, i; 
MPI_Status status; 
char message[20]; 
char new_message[20]; 
MPI_Init(&argc, &argv); 
MPI_Comm_size(MPI_COMM_WORLD, &size); 
MPI_Comm_rank(MPI_COMM_WORLD, &rank); 
tag=7; 

if (rank==0) { 
    strcpy(message, "Hello, world"); 
    for (int i=1; i<size; ++i){ 
     list<int> rand_list; 
     list<int>::iterator it = rand_list.end(); 
     list<int> *lt_ptr = &rand_list; 
     for(int j = 0; j < 5; ++j) 
     { 
      int r; 
      r = rand(); 
      rand_list.push_front(r); 
      it++; 
     } 
     //Instead of sending the string I'd like to send the list of random ints 
     MPI_Send(message, 13, MPI_CHAR, i, tag, MPI_COMM_WORLD); 
     MPI_Recv(new_message, 13, MPI_CHAR, i, tag, MPI_COMM_WORLD, &status); 
     cout << "master: " << new_message << endl; 
     } 
} 
else{ 
    // slaves processes 
    rc = MPI_Recv(message, 13, MPI_CHAR, 0, tag, MPI_COMM_WORLD, &status); 
    cout << "node " << rank << ": " << message << endl; 
    strcpy(new_message, "Goodbye, world"); 
    // code to manipulate the lists and send back to the master process 
    rc = MPI_Send(new_message, 13, MPI_CHAR, 0, tag, MPI_COMM_WORLD); 
    } 
MPI_Finalize(); 
} 

下面是我用来编译和运行的命令。

mpic++ mpi_prog.cpp -o mpi_prog.o 
mpirun -np 5 mpi_prog.o 
+1

如果您只是使用'std :: vector '而不是'std :: list ',这就变得微不足道了。发送缓冲区是'&rand_vec [0]',计数是'rand_vec.size()'。是否有特别需要使用列表? – Novelocrat

回答

0

为什么要在这里使用std::liststd::vector似乎更合适,数据连续存储,它应该直接与MPI一起工作。你是过于复杂的东西,并喜欢使用std::uniform_int_distribution而不是std::rand

你的主代码来填充随机向量应该像这样的事情:

std::vector<int> v(5); 
std::random_device rd; 
std::mt19937 gen(rd()); // mersenne twister engine 
std::uniform_int_distribution<> dis; 
std::generate(v.begin(), v.end(), [&](){ return dis(gen); }); // fill the vector with random values 

你的主节点可以在MPI直接拨打:

MPI_Send(&v[0], v.size(), MPI_INT, i, tag, MPI_COMM_WORLD); 

从节点代码:

MPI_Recv(&v[0], v.size(), MPI_INT, 0, tag, MPI_COMM_WORLD, &status); 

我不确定这是你想要做的。您的主站将初始化具有随机值的size不同向量,并将它们中的每一个发送到一个从节点。从机接收的每个矢量都不相同。这是对的吗 ?

0

发送列表的最简单的方法可能是通过发送列表的长度,你有5,然后在元素的循环由一个送他们一个。这会有很差的性能,但使用列表可能是一个有问题的设计选择,原因很多。

由于您也在主控制器中逐一循环处理,向每个不同的数字发送它们,因此可能会更好地使用不同的总体设计。对于您的特定用例,如何在实际使用它们的进程上并行生成随机数字。有专门设计的并行随机数生成算法和先进的随机数生成器,您可以告诉每个从机在流中跳过多远以避免重叠。