问题描述
我正在尝试使用MPI在C ++中编写并行代码,但是我只知道如何使用C命令(如malloc/calloc)分配内存.目的是使用身份矩阵并将其分解为MPI流程.
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. The aim is to work with the identity matrix and decompose it among the MPI processes.
在本地工作空间上创建身份矩阵,然后将其从本地发送到等级0以进行打印.
The identity matrix is created on the local workspace and then sent from local to rank 0 to be printed.
我尝试过的代码段是:
使用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));
使用C ++语言分配内存:
Allocating memory using C++ language:
int** matrix = new int *[row];
我成功地使用C编程语言运行,无论如何我想重写C ++的代码.
I succeed to run on C programming language, how ever I would like to rewrite the code for C++.
推荐答案
让连续数组与MPI
一起使用非常方便,特别是对连续数据进行编码要容易得多,例如制作派生数据类型.我的建议是使用vector
并展平您的数据:
It is quite handy to have contiguous array working with MPI
specially it is much easier to code with contiguous data e.g. to make derived data types. My recommendation is using vector
and flattening your data:
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
您还可以使用智能指针:
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;
不好的方法是:
警告,您将进入***程序员国.
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;
和 godbolt
这篇关于如何在C ++中使用MPI而不是C malloc/calloc动态分配内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!