如何在 C++ 中使用 MPI 而不是 C malloc/calloc 动态分配内存?

How to dynamically allocate memory using MPI in C++ instead of C malloc/calloc?

我正在尝试使用 MPI 在 C++ 中编写并行代码,但是我只知道如何使用 C 命令分配内存,如 malloc/calloc。目的是使用单位矩阵并在 MPI 进程中分解它。

在本地工作区创建单位矩阵,然后从本地发送到秩 0 进行打印。

我试过的代码有:

使用C语言分配内存:

// N is the matrix size (N x N)
int* A=( int* )calloc( local_N*N, sizeof(int) );
typedef int row[N];
row *mat;

/* Dividing the number of rows to each processor*/

int n = N / size;

mat = (row *) malloc(n * sizeof(row));

使用 C++ 语言分配内存:

 int**  matrix = new int *[row];

我在C语言上运行成功了,我怎么想重写C++的代码。

让连续数组与 MPI 一起工作非常方便,特别是使用连续数据编码更容易,例如制作 derived data types。我的建议是使用 vector 并展平您的数据:

const int N = 100;
const int M = 20;
const int size = 4;
int n = N / size;
std::vector<int> mat(n*M); // each process has a mat with length of n * M
for(uint32_t i = 0; i < n; ++i)
    for(uint32_t j = 0; j < M; ++j)
        mat.at(i * M + j) = j; // this is equivalent to mat[i][j] if mat was 2D

你也可以使用smart pointers:

using ManagedInt = std::unique_ptr<int[]> ;
auto managedMat = std::unique_ptr<ManagedInt[]>(new ManagedInt[n]);
for (size_t i = 0; i < n; ++i)
    managedMat[i] = ManagedInt(new int[M]);

for(uint32_t i = 0; i < n; ++i)
    for(uint32_t j = 0; j < M; ++j)
       managedMat[i][j] = j;

不好的方法是:

警告您即将进入 ***程序员之地。

// allocate mat
int **mat = new int *[n];
for (int i = 0; i < n; i++) {
    mat[i] = new int [M];
}

// now you can use mat[i][j]

// delete mat
for (int i = 0; i < n; i++) {
    delete[] mat[i];
}
delete[] mat;

godbolt