arrays - MPI 广播二维阵列

标签 arrays mpi broadcast

我打算使用 MPI 来学习并行编程。我有一些错误

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


int main(int argc, char** argv)
{
    int procNum, procRank;
    int m,n;
    int sumProc = 0, sumAll = 0;
    int** arr;
    MPI_Status status;

    MPI_Init ( &argc, &argv );

    MPI_Comm_size ( MPI_COMM_WORLD, &procNum ); 
    MPI_Comm_rank ( MPI_COMM_WORLD, &procRank );

    if (procRank == 0)
    {   
        printf("Type the array size \n");
        scanf("%i %i", &m, &n); 
    }
    MPI_Bcast(&m, 1, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);

    arr = new int*[m];
    for (int i = 0; i < m; i++)
        arr[i] = new int[n];

    if (procRank == 0)
    {
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                    arr[i][j] = rand() % 30;
                    printf("%i ", arr[i][j]);
            }
            printf("\n");
        }
    }

    MPI_Bcast(&arr[0][0], m*n, MPI_INT, 0, MPI_COMM_WORLD);

    for (int i = procRank; i < n; i += procNum)
        for (int j = 0; j < m; j++)
            sumProc += arr[j][i];

    MPI_Reduce(&sumProc,&sumAll,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD);

    if (procRank == 0)
    {
        printf("sumAll = %i", sumAll);
    }

    delete *arr;

    MPI_Finalize();
    return 0;
}

我试图将二维数组传递给其他进程,但是当我检查它时,我得到了错误的数组。 像这样的事情:

Original array
11 17 4
10 29 4
18 18 22

Array which camed
11 17 4
26 0 0
28 0 0

这是什么问题?也许问题出在 MPI_Bcast

附注我添加了

for (int i = 0; i < m; i++)
    MPI_Bcast(arr[i], n, MPI_INT, 0, MPI_COMM_WORLD);

而不是

MPI_Bcast(&arr[0][0], m*n, MPI_INT, 0, MPI_COMM_WORLD);

解决了我的问题

最佳答案

这里

arr = new int*[m];
for (int i = 0; i < m; i++)
    arr[i] = new int[n];

首先创建一个指针数组,然后为每个指针创建常规 int 数组,从而创建一个 2D 数组。使用此方法,所有数组 a[i] 的大小均为 n 个元素,但不保证在内存中是连续的。

然而,后来,

MPI_Bcast(&arr[0][0], m*n, MPI_INT, 0, MPI_COMM_WORLD);

您假设所有数组在内存中都是连续的。因为它们不是,所以你会得到不同的值。

关于arrays - MPI 广播二维阵列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18945129/

相关文章:

c - 如何使我的递归 C 程序更有效率?

performance - tau_exec 无法启动, "error no matching binding for ' mpi'"

linux - 如何观察 MPI 程序所有进程的运行时间

android - 权限拒绝 : not allowed to send broadcast android. intent.action.AIRPLANE_MODE

c++ - 在 C++ 中,如何从 B 类访问 Class 中的多维数组?

java - 如何在java中仅打印数组中的填充值?

parallel-processing - 为共享内存配置 MPI 是什么意思?

image - 推送图像 Vaadin Java

python - 将函数广播到 3D 数组 Python

c++ - 如何从 .t​​xt 文件读取 CSV 列表并将每个项目分隔到自己的数组中