3
我正要學習MPI的並行編程。我有一些錯誤MPI廣播2d陣列
#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;
}
我想通過2d數組到其他進程,但是當我檢查出來,我得到錯誤的數組。 事情是這樣的:
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
P.S.我加
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);
它解決了我的問題
它看起來好像在你的不成功的版本中,你錯誤地認爲數組在內存中是連續的。 –