简体   繁体   English

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

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

I am trying to write a parallel code in C++ employing MPI, however I only know how to allocate memory using the C commands, as malloc/calloc. 我正在尝试使用MPI在C ++中编写并行代码,但是我只知道如何使用C命令(如malloc / calloc)分配内存。 The aim is to work with the identity matrix and decompose it among the MPI processes. 目的是使用身份矩阵并在MPI流程之间分解它。

The identity matrix is created on the local workspace and then sent from local to rank 0 to be printed. 身份矩阵在本地工作空间上创建,然后从本地发送到要打印的等级0。

The pieces of codes that I have tried are: 我尝试过的代码片段是:

Allocating memory using C language: 使用C语言分配内存:

  • calloc 卡洛克
// N is the matrix size (N x N)
int* A=( int* )calloc( local_N*N, sizeof(int) );
  • malloc 分配
typedef int row[N];
row *mat;

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

int n = N / size;

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

Allocating memory using C++ language: 使用C ++语言分配内存:

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

I succeed to run on C programming language, how ever I would like to rewrite the code for C++. 我成功地使用C编程语言运行,无论如何我想重写C ++的代码。

It is quite handy to have contiguous array working with MPI specially it is much easier to code with contiguous data eg to make derived data types . 使用MPI连续数组是非常方便的,特别是使用连续数据进行代码编写(例如派生数据类型)容易得多。 My recommendation is using vector and flattening your data: 我的建议是使用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

You can also use smart pointer s: 您还可以使用智能指针 s:

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;

The bad way is: 坏方法是:

WARNING you are about to enter ***programmer land. 警告您将要进入程序员领域。

// 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;

and the godbolt 上帝的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM