【问题标题】:MPI send matrix columns (C++) [duplicate]MPI发送矩阵列(C++)[重复]
【发布时间】:2015-03-19 00:23:50
【问题描述】:

我尝试将矩阵的第二列和第三列从排名为 1 的进程和 MPI 为 2 的进程发送到排名为 0 的进程。

在网上找到了这个例子http://www.mcs.anl.gov/research/projects/mpi/mpi-standard/mpi-report-1.1/node70.htm#Figure4并写了一段代码:

#include <iostream>
#include <mpi.h>

using namespace std;

int main(int argc, char *argv[]) {
    int id;
    int matrix[3][3];
    int matrixB[9];

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &id);

    for(int i=0; i<3; i++)
        for(int j=0; j<3; j++)
            if(id == 0)
                matrix[i][j] = 0;
            else
                matrix[i][j] = j+1;

    MPI_Datatype matrixSpalte;

    MPI_Type_vector(3, 1, 3, MPI_INT, &matrixSpalte);
    MPI_Type_commit(&matrixSpalte);

    MPI_Gather(&matrix[0][id], 1, matrixSpalte, &matrixB[0], 1, matrixSpalte, 0, MPI_COMM_WORLD);

    if(id == 0)
        for(int i=0; i<9; i++) {
            if(i % 3 == 0)          
                cout << endl;

            cout << matrixB[i] << " (" << i << ") ";

        }


    MPI_Finalize();
    return 0;
}

但输出是:

0 (0) 0 (1) 1351992736 (2)
0 (3) 254423040 (4) 1 (5)
0 (6) 2 (7) 1351992752 (8)

应该是:

1 (0) 2 (1) 3 (2)
1 (3) 2 (4) 3 (5)
1 (6) 2 (7) 3 (8)

我不知道为什么这不起作用。希望有人能帮我找出代码中的错误。

您的真诚,

亨氏

解决方案(感谢 Jonathan Dursi):

#include <iostream>
#include <mpi.h>

using namespace std;

int main(int argc, char *argv[]) {
    int id;
    int matrix[3][3];
    int matrixB[9];

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &id);

    for(int i=0; i<3; i++)
        for(int j=0; j<3; j++)
            if(id == 0)
                matrix[i][j] = 0;
            else
                matrix[i][j] = j+1;

    MPI_Datatype matrixSpalte, tmp;

    MPI_Type_vector(3, 1, 3, MPI_INT, &tmp);
    MPI_Type_create_resized(tmp, 0, sizeof(int), &matrixSpalte);  // !!!
    MPI_Type_commit(&matrixSpalte);

    MPI_Gather(&matrix[0][id], 1, matrixSpalte, matrixB, 1, matrixSpalte, 0, MPI_COMM_WORLD);

    if(id == 0)
        for(int i=0; i<9; i++) {
            if(i % 3 == 0)          
                cout << endl;

            cout << matrixB[i] << " (" << i << ") ";

        }


    MPI_Finalize();
    return 0;
}

【问题讨论】:

  • 您需要调整矢量类型的大小以在这样的集合中使用它 - 例如,MPI_Type_vector(3, 1, 3, MPI_INT, &amp;tmp); MPI_Type_create_resized(tmp, 0, sizeof(int), &amp;matrixSpalte); MPI_Type_commit(&amp;matrixSpalte);。有关原因的解释,请参阅this answer
  • 如果你确实有解决方案,你应该回答你自己的问题并相应地标记它,而不是把答案放在问题中。

标签: c++ matrix mpi send


【解决方案1】:

MPI_Gather 应该传递一个缓冲区,该缓冲区可以将所有元素存储在一个连续的数组中。看看the picture here

rbuf必须指向一个由9个ints组成的数组。这就是您收到Abort trap: 6 错误的原因,正如here 所解释的那样。您正在尝试通过matrix[0][8]matrix[0][3]

另外,您的recv_type 必须是MPI_INT

【讨论】:

  • 谢谢。我将接收数据类型更改为一维数组。但遗憾的是,这并没有解决整个问题。 (我在最初的帖子中写了新的输出和源代码)
  • 是的,忘了一件事。更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-21
  • 2013-03-05
  • 2013-12-23
  • 2013-12-18
  • 1970-01-01
  • 2021-06-13
相关资源
最近更新 更多