我正在尝试使用 MPI 在 N 个进程中划分 2D 矩阵的列。对于模板,我使用了MPI_Scatter 上的示例 - 发送 2D 数组的列。
我的代码:
//HEADERS
char** board_initialize(int n, int m)
{
int k, l;
char* bd = (char*)malloc(sizeof(char) * n * m);
char** b = (char**)malloc(sizeof(char*) * n);
for (k = 0; k < n; k++)
b[k] = &bd[k * m];
for (k = 0; k < n; k++)
for (l = 0; l < m; l++)
b[k][l] = rand() < 0.25 * RAND_MAX;
return b;
}
void board_print(char** b, int n, int m)
{
int k, l;
// system("@cls||clear");
for (k = 0; k < n; k++)
{
for (l = 0; l < m; l++)
printf("%d", b[k][l]);
printf("\n");
}
printf("\n");
}
int main(int argc, char* argv[])
{
int N = 10;
int i, j;
char * boardptr = NULL; // ptr to board
char ** board; // board, 2D matrix, contignous memory allocation!
int procs, myid;
int mycols;
char ** myboard; // part of board that belongs to a process
MPI_Init(&argc, &argv); // initiailzation
MPI_Comm_rank(MPI_COMM_WORLD, &myid); // process ID
MPI_Comm_size(MPI_COMM_WORLD, &procs); // number of processes
// initialize global board
if (myid == 0)
{
srand(1573949136);
board = board_initialize(N, N);
boardptr = *board;
board_print(board, N, N);
}
// divide work
mycols = N / procs;
// initialize my structures
myboard = board_initialize(N,mycols);
MPI_Datatype column_not_resized, column_resized;
MPI_Type_vector(N, 1, N, MPI_CHAR, &column_not_resized);
MPI_Type_commit(&column_not_resized);
MPI_Type_create_resized(column_not_resized, 0, 1*sizeof(char), &column_resized);
MPI_Type_commit(&column_resized);
// scatter initial matrix
MPI_Scatter(boardptr, mycols, column_resized, *myboard, mycols, column_resized, 0, MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
board_print(myboard, N, mycols);
MPI_Finalize(); // finalize MPI
return 0;
}
整个板子看起来像:
0000010010
0100000000
0000101100
0101000010
1000000100
0000010010
0000001110
0110000100
0000100000
0100010010
如果我使用 2 个进程,我希望每个进程都会得到一半(第一个进程列 1-5 和第二个进程列 6-10)。但是,如果我打印这两个过程的myboard,我会得到一些奇怪的结果:
proc0: proc1:
0 0 0 0 0 1 0 0 1 0
0 0 1 0 0 0 0 0 1 1
0 1 0 0 0 0 0 0 0 0
0 1 0 0 0 0 1 0 1 0
0 0 0 0 1 0 1 1 0 0
0 1 1 0 0 0 0 1 0 0
0 1 0 1 0 0 0 0 1 0
0 0 0 0 1 0 0 1 0 0
1 0 0 0 0 0 0 1 0 0
0 1 0 0 0 0 1 0 0 0
这可能是一些愚蠢的错误,但我似乎无法找到它。任何帮助将非常感激。<3
注意:proc1 的输出可能只是一些垃圾,因为每次运行我都会得到不同的输出。