如何使用 MPI 在 Eigen::MatrixXd 中发送数据

How to send the data in an Eigen::MatrixXd with MPI

我想使用 MPI 在机器之间发送矩阵。以下是我的测试代码

#include <iostream>
#include <Eigen/Dense>
#include <mpi.h>
using std::cin;
using std::cout;
using std::endl;
using namespace Eigen;

int main(int argc, char ** argv)
{
    MatrixXd a = MatrixXd::Ones(3, 4);
    int myrank;
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
    MPI_Status status;
    if (0 == myrank)
    {
        MPI_Send(&a, 96, MPI_BYTE, 1, 99, MPI_COMM_WORLD);
    }
    else if (1 == myrank)
    {
        MPI_Recv(&a, 96, MPI_BYTE, 0, 99, MPI_COMM_WORLD, &status);
        cout << "RANK " << myrank << endl;
        cout << a << endl;
    }
    MPI_Finalize();
    return 0;
}

编译成功没有错误,但是当我启动它的时候,却返回如下错误。

$ MPI mpiexec -n 2 ./sendMatrixTest
RANK 1
[HPNotebook:11633] *** Process received signal ***
[HPNotebook:11633] Signal: Segmentation fault (11)
[HPNotebook:11633] Signal code: Address not mapped (1)
[HPNotebook:11633] Failing at address: 0xf4ba40
--------------------------------------------------------------------------
mpiexec noticed that process rank 1 with PID 11633 on node HPNotebook exited on signal 11 (Segmentation fault).
--------------------------------------------------------------------------

我该如何解决?谢谢!

正如@Matt 指出的那样,MatrixXd 容器中的内容不仅仅是数据。然而,由于在这里您知道矩阵的大小和类型,您可以使用 data() method 获取指向普通旧数据的指针,这样就可以了:

#include <iostream>
#include <Eigen/Dense>
#include <mpi.h>
using std::cin;
using std::cout;
using std::endl;
using namespace Eigen;

int main(int argc, char ** argv)
{
    MatrixXd a = MatrixXd::Ones(3, 4);
    int myrank;
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
    MPI_Status status;
    if (0 == myrank)
    {
        MPI_Send(a.data(), 12, MPI_DOUBLE, 1, 99, MPI_COMM_WORLD);
    }
    else if (1 == myrank)
    {
        MPI_Recv(a.data(), 12, MPI_DOUBLE, 0, 99, MPI_COMM_WORLD, &status);
        cout << "RANK " << myrank << endl;
        cout << a << endl;
    }
    MPI_Finalize();
    return 0;
}