[英]An MPI program crashes after it's done printing output
以下程序(來自這個已刪除的問題)似乎是正確的,但在打印結果后卻神秘地崩潰了。 我已經按原樣粘貼了程序 - 看看你是否能發現錯誤:)
#include <assert.h>
#include <memory.h>
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char ** argv) {
MPI_Init(&argc, &argv);
int n = 16;
int npow2 = 16 * 16;
int world_size;
int b[n][n];
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
int m = world_size;
int reg = npow2 / m;
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int fstart = rank * reg;
int fend = fstart + reg;
int myres[reg];
int mystart = (int)(fstart / n);
int myend = (int)(fend / n);
int dim = myend - mystart;
int a[dim][n];
int i, j, k = 0;
//all processes
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
b[i][j] = (i + 1) * (j + 1);
}
}
//eaach process initialize its contribution
int tmpi = 0;
for (i = mystart; i < myend; i++) {
for (j = 0; j < n; j++) {
a[tmpi][j] = (i + 1) * (j + 1);
}
tmpi++;
}
int inx = 0;
for (i = 0; i < dim; i++) {
for (j = 0; j < n; j++) {
myres[inx] = 0;
int tmpres = 0;
for (k = 0; k < n; k++) {
tmpres = a[i][k] * b[k][j];
myres[inx] = myres[inx] + tmpres;
}
inx++;
if (inx >= reg) goto xlabel;
}
}
xlabel:
MPI_Barrier(MPI_COMM_WORLD);
int * recvmatrix = NULL;
if (rank == 0) {
recvmatrix = malloc(sizeof(int) * npow2);
}
assert(world_size * reg == npow2);
MPI_Gather(myres, reg, MPI_INT, recvmatrix, reg, MPI_INT, 0, MPI_COMM_WORLD);
if (rank == 0) {
for (i = 0; i < npow2; i++) {
printf("%d,", recvmatrix[i]);
if (((i + 1) % n) == 0) printf("\n");
}
}
MPI_FINALIZE();
free(recvmatrix);
}
下面的“修復”,包括一個包含和兩個添加的行,圍繞着這個問題,允許程序在不崩潰根實例的情況下完成。
#include <unistd.h>
...
if (rank == 0) {
for (i = 0; i < npow2; i++) {
printf("%d,", recvmatrix[i]);
if (((i + 1) % n) == 0) printf("\n");
}
fflush(stdout); // < added
_exit(0); // < added
}
這是怎么回事?
提示:提問者沒有提到編譯器發出了關於隱式 function 聲明的警告。
事實證明,不知何故,該程序是使用
-lmpi
和-lmpi_mpifh
(或等效項)構建的,即也與 FORTRAN 庫鏈接。 也許學生被指示這樣做,或者另一個學生“幫助”了他們,或者他們自己想出了如何“修復” linker 錯誤 - 我只能推測。MPI_FINALIZE()
triggers a C compiler warning, since it's not a part of the C API, but it will happily link - with the Fortran function, in all its uppercase glory. 當然,它會崩潰。 以下命令行在gcc -o mpi mpi.c -lmpi -lmpi_mpifh -I /usr/lib/include/openmpi; mpirun./mpi
上重現此塊:gcc -o mpi mpi.c -lmpi -lmpi_mpifh -I /usr/lib/include/openmpi; mpirun./mpi
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.