gpt4 book ai didi

在 MPI 上创建结构和 union

转载 作者:太空宇宙 更新时间:2023-11-04 03:52:31 25 4
gpt4 key购买 nike

编辑:感谢之前的帮助。我真的很感激。

我是否也应该从 *list 中删除指针?为了创建 atributo 和 estrucura,我也在使用指针,这也会有问题吗?

union atributo{
int valor1;
char valor2[tamChar];
float valor3;
};


struct estructura{
int tipo[tamEstruct]; //Here i will have an array with the types of the union
union atributo *list[tamEstruct];

};

union atributo *atributos;
struct estructura *estructuras;

estructuras = malloc (sizeof(struct estructura) * (cantEstruct) );



MPI_Datatype atributo_MPI;
MPI_Datatype type[1] = { MPI_BYTE };
int blocklen[1] = { tamChar }; // the largest element is the chat
MPI_Aint disp[1];

disp[0]= atributos[0]; // the begin of the union



MPI_Datatype estructura_MPI;
MPI_Datatype type[2] = { MPI_INT, atributo_MPI };
int blocklen[2] = { tamEstruct, tamEstruct};
MPI_Aint disp2[2];

disp2[0]= offsetof(atributos, tipo);
disp2[1]= offsetof(atributos, list);

我接近正确的代码了吗?

最佳答案

那段代码有几处错误。

首先,在这种情况下,结构和 union 非常不同。结构包含列出的每个元素,在内存中一个接一个地排列。另一方面, union 仅与其最大元素一样大,并且其所有成员共享相同的内存空间(好像它们是结构的唯一成员)。这意味着您不能将 union 打包到 MPI_Struct 中,因为每个成员的偏移量实际上都是 0。

有两种方法可以解决 union 数组的问题:

  • 将它们作为 MPI_BYTE 数组发送。这很简单,但如果您的进程不共享相同的数据表示(例如,它们的整数在字节序上不同),则存在数据损坏的风险。
  • 使用MPI_Pack() 将值一个一个打包。这是类型安全的,但更复杂,并且会生成数据的内存副本。

请注意,在任何一种情况下,接收进程都需要知道它接收到的值(即,如果它接收到 3 个 union ,是那 3 个整数,还是 2 个整数和一个 float ,等等)。如果您使用 union ,您也必须发送此信息。

您可能需要考虑一种更棘手的方法:根据哪个值有效对枚举进行分组,并发送一条消息,其中相似的枚举彼此相邻放置(例如,包含 数组的消息MPI_INT,然后是 MPI_FLOAT 的数组等等)。通过巧妙地使用派生的 MPI 数据类型,您可以保持类型安全,避免内存中复制,避免发送多条消息。


第二:永远不要在 MPI 进程之间发送指针!很容易将 char* 视为 char 的数组,但事实并非如此。它只是一个内存地址,对您将其发送到的进程没有意义,即使有,您实际上也没有发送它指向的数据。如果 valor2 是一个具有相当短的最大长度的字符串,我建议将它声明为 char valor2[maxLength] 以便它的内存分配在实际结构/联盟。如果这不可行,您将不得不做更多的内存杂耍,以将您的字符串传递给其他进程,就像处理任何可变大小的数组一样。

关于在 MPI 上创建结构和 union ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19637159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com