【发布时间】:2019-01-10 01:03:13
【问题描述】:
MPI documentation 断言接收缓冲区的地址 (recvbuf) 仅在根处有效。这意味着内存可能不会在其他进程中分配。 this question 确认了这一点。
int MPI_Reduce(const void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype,
MPI_Op op, int root, MPI_Comm comm)
起初我认为recvbuf 甚至不必存在:recvbuf 本身的内存不必分配(例如通过动态分配)。不幸的是(我花了很多时间才理解我的错误!),似乎即使它指向的内存无效,指针本身也必须存在。
请参阅下面的代码,了解我想到的代码,其中一个版本会产生段错误,而另一个版本不会。
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
int main(int argc, char **argv) {
// MPI initialization
int world_rank, world_size;
MPI_Init(NULL, NULL);
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
int n1 = 3, n2 = 10; // Sizes of the 2d arrays
long **observables = (long **) malloc(n1 * sizeof(long *));
for (int k = 0 ; k < n1 ; ++k) {
observables[k] = (long *) calloc(n2, sizeof(long));
for (long i = 0 ; i < n2 ; ++i) {
observables[k][i] = k * i * world_rank; // Whatever
}
}
long **obs_sum; // This will hold the sum on process 0
#ifdef OLD // Version that gives a segfault
if (world_rank == 0) {
obs_sum = (long **) malloc(n2 * sizeof(long *));
for (int k = 0 ; k < n2 ; ++k) {
obs_sum[k] = (long *) calloc(n2, sizeof(long));
}
}
#else // Correct version
// We define all the pointers in all the processes.
obs_sum = (long **) malloc(n2 * sizeof(long *));
if (world_rank == 0) {
for (int k = 0 ; k < n2 ; ++k) {
obs_sum[k] = (long *) calloc(n2, sizeof(long));
}
}
#endif
for (int k = 0 ; k < n1 ; ++k) {
// This is the line that results in a segfault if OLD is defined
MPI_Reduce(observables[k], obs_sum[k], n2, MPI_LONG, MPI_SUM, 0,
MPI_COMM_WORLD);
}
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
// You may free memory here
return 0;
}
我的解释正确吗?这种行为背后的原因是什么?
【问题讨论】:
-
world_rank == 0是真还是假?你认为long **obs_sum;会发生什么,然后你在没有初始化obs_sum的情况下执行obs_sum[k]? -
你了解MPI吗?该程序将在多个副本(进程)中发送,其中 world_rank = 0, 1, 2, ...
obs_sum将仅在进程 0 上使用(这就是为什么obs_sum[k]不需要分配)。我的问题是:如果obs_sum在进程 1、2 上完全没用......为什么它必须存在? -
也就是说,你应该是对的,写
obs_sum[k]可能意味着它即使完全没用也被分配了。 -
obs_sum[k]等于*(obs_sum + k)并且只有 writing 它足以让 * 运算符在无效的指针值上执行(因为obs_sum未初始化),这对于未定义的行为和段错误来说已经足够了。所以world_rank是!= 0,对吧?