我将尝试使用MPI库编写一个C程序,其中主进程创建一个二维数组并将其行分配给其他进程。该矩阵的维度为
以下是代码:
运行此代码时我收到的输出结果是:
p*p
,其中p
是进程数。以下是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mpi.h>
int **createMatrix (int nrows, int ncols) {
int **matrix;
int h, i, j;
if (( matrix = malloc(nrows*sizeof(int*))) == NULL) {
printf("Malloc error");
exit(1);
}
for (h=0; h<nrows; h++) {
if (( matrix[h] = malloc( ncols * sizeof(int))) == NULL) {
printf("Malloc error 2");
exit(1);
}
}
for (i=0; i<ncols; i++) {
for (j=0; j<nrows; j++) {
matrix[i][j] = ((i*nrows) + j);
}
}
return matrix;
}
void printArray (int *row, int nElements) {
int i;
for (i=0; i<nElements; i++) {
printf("%d ", row[i]);
}
printf("\n");
}
void printMatrix (int **matrix, int nrows, int ncols) {
int i;
for (i=0; i<nrows; i++) {
printArray(matrix[i], ncols);
}
}
int main (int argc, char **argv) {
if (MPI_Init(&argc, &argv) != MPI_SUCCESS) {
perror("Error initializing MPI");
exit(1);
}
int p, id;
MPI_Comm_size(MPI_COMM_WORLD, &p); // Get number of processes
MPI_Comm_rank(MPI_COMM_WORLD, &id); // Get own ID
int **matrix;
if (id == 0) {
matrix = createMatrix(p, p); // Master process creates matrix
printf("Initial matrix:\n");
printMatrix(matrix, p, p);
}
int *procRow = malloc(sizeof(int) * p); // received row will contain p integers
if (procRow == NULL) {
perror("Error in malloc 3");
exit(1);
}
if (MPI_Scatter(*matrix, p, MPI_INT, // send one row, which contains p integers
procRow, p, MPI_INT, // receive one row, which contains p integers
0, MPI_COMM_WORLD) != MPI_SUCCESS) {
perror("Scatter error");
exit(1);
}
printf("Process %d received elements: ", id);
printArray(procRow, p);
MPI_Finalize();
return 0;
}
运行此代码时我收到的输出结果是:
$ mpirun -np 4 test
Initial matrix:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
Process 0 received elements: 0 1 2 3
Process 1 received elements: 1 50 32 97
Process 2 received elements: -1217693696 1 -1217684120 156314784
Process 3 received elements: 1 7172196 0 0
0号进程似乎收到了正确的输入,但其他进程显示的数字我无法理解。此外,请注意,程序的多次运行中,1号和3号进程的数字是一致的,而2号进程的数字在每次运行时都会改变。
我觉得我的内存分配或指针使用有问题,但我对C编程还很陌生。有人能向我解释一下这种输出是如何产生的吗?其次,我也很想知道如何解决我的问题 :) 提前感谢!