首页 > 解决方案 > 如何正确创建 MPI 自定义类型

问题描述

我有结构(复杂矩阵的单个元素):

typedef struct  s_complex_number {
    int real;
    int img;
}               ComplexNumber;

这就是我将复杂矩阵描述为自定义 MPI 数据类型的方式

#define SIZE_COL 10
MPI_Datatype  matrix;
MPI_Datatype  types[2] = {MPI_INT, MPI_INT};
MPI_Datatype  row;
MPI_Datatype  complexNumber;
MPI_Aint      disp[2];
ComplexNumber ***recvData;
ComplexNumber ***sendData;
ComplexNumber example;

int blockLength[] = {1, 1};

disp[0] = (uintptr_t)&example.real - (uintptr_t)&example;
disp[1] = (uintptr_t)&example.img - (uintptr_t)&example;

/***********************Initialize custom types************************/
MPI_Type_create_struct(2, blockLength, disp, types, &complexNumber);
MPI_Type_commit(&complexNumber);

MPI_Type_vector(1, SIZE_COL, 1, complexNumber, &row);
MPI_Type_commit(&row);

MPI_Type_vector(1, SIZE_COL, 1, row, &matrix);
MPI_Type_commit(&matrix);
/**********************************************************************/

每次我尝试发送数据时,都会出现分段错误。

如何正确描述 MPI 中的 ComplexNumber** 类型?

标签: ctypessegmentation-faultmpi

解决方案


使用 MPI发送/接收ComplexNumber ***mat非常麻烦。您需要创建一个结构数据类型,其中的字段数与行数一样多mat,然后将每个字段的偏移量设置为相应行开头的绝对地址,最后MPI_BOTTOM用作发送/接收中的缓冲区地址称呼:

MPI_Datatype theMatrix;
MPI_Datatype types[SIZE_COL];
MPI_Aint disps[SIZE_COL];
int blocklengts[SIZE_COL];

for (int i = 0; i < SIZE_COL; i++)
{
   types[i] = row;
   disps[i] = (MPI_Aint) (*mat)[i];
   blocklents[i] = 1;     
}

MPI_Type_create_struct(SIZE_COL, blocklengths, disps, types, &theMatrix);
MPI_Type_commit(&theMatrix);

MPI_Send(MPI_BOTTOM, 1, theMatrix, ...);

MPI_Type_free(&theMatrix);

注意事项:

  • theMatrix只能用于发送mat-mat没有其他指向指针数组对象的指针可能使每一行都位于内存中的相同地址。这就是为什么theMatrix在调用 之后立即被释放的原因MPI_Send,因为它没有用,除非矩阵空间将被重复使用并一次又一次地发送。
  • 结构字段的偏移量是行的地址。可以使用(char *)(*mat)[i] - (char *)mat,但这样更麻烦。
  • 由于偏移量是绝对地址,MPI_BOTTOM因此被指定为缓冲区地址。这本质0上是地址空间的底部。如果(char *)(*mat)[i] - (char *)mat用于代替偏移量,那么您必须提供mat代替MPI_BOTTOM.

另一方面,发送/接收平面矩阵,即

ComplexNumber *mat = malloc(SIZE_COL * SIZE_COL * sizeof(ComplexNumber));

归结为:

MPI_Send(mat, 1, matrix, ...);

这就是按照您的代码创建的数据类型所描述的内存布局。


推荐阅读