c++ - 在 MPI、C++ 上分配单个堆栈数组

标签 c++ multithreading memory scope mpi

问题来了。我有一些“小”数组,我不想将它们 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/

相关文章:

java - 进度条更新程序占用 CPU

c++ - VC++ : Performance drop x20 when more threads than cpus but not under g++

android - 长按 surfaceView ( android )

mysql - 如何确保内存消耗不随 redis 数据库的大小而缩放

c++ - 多个文件中的全局变量

java - 等价于cin.tie(0)在Java中吗?

c++ - top 如何查看内存使用情况

c - 用指针访问零位

c++ - 如何在 Qt 中声明和使用二维整数数组(GUI)?

c++ - 在 gnu radio 中编译出树模型时出现 CMake 错误