问题来了。我有一些“小”数组,我不想将它们 MPI_Gather 变成一个大数组,但我只想在根 (0) 线程上分配一个大数组。
#include <mpi.h>
#include <iostream>
int main(int argc, char **argv) {
int rank, numprocs;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
MPI_Status status;
int N = 5;
int x[N] = {1,2,3,4,5};
int big_x[numprocs*N];
MPI_Gather(x, N, MPI_INT, big_x, N, MPI_INT, 0, MPI_COMM_WORLD);
if (rank == 0) {
for (int i=0; i<numprocs*N; ++i)
std::cout << big_x[i] << std::endl;
}
MPI_Finalize();
return 0;
}
这是工作代码,但如您所见,我在每个线程上都分配了 big_x。如果我只想在一个线程中分配它怎么办?我会得到一个范围错误。我应该只使用动态内存吗?
最佳答案
是的,你应该使用动态内存。
int *big_x = NULL;
if (rank == 0) big_x = new int[numprocs*N];
...
if (rank == 0) delete [] big_x;
静态数组的大小应该是常量。
所以 int big_x[numprocs*N]
是一个错误,因为它在函数开始时分配,在 numprocs
初始化之前。
还有
int N = 5;
int x[N] = {1,2,3,4,5};
是一个错误,因为 N
不是常量。
请改用 const int N = 5
或 #define N 5
。
关于c++ - 在 MPI、C++ 上分配单个堆栈数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39541517/