c - MPI 上带有指针的结构

标签 c pointers struct mpi

我正在尝试在 MPI 上发送以下结构:

union atributo{
    int valor1;
    char *valor2;  
    float valor3;
};


struct estructura{
    int *tipo;
    union atributo *list;

};

我知道它们是动态指针,但我需要使用它们。我有相同的结构和静态指针工作,但使用这个我不能让它们工作。

MPI 结构是:

MPI_Datatype atributo_MPI;
MPI_Datatype type[1] = { MPI_BYTE };
int blocklen[1] = { (tamChar +1) };
MPI_Aint disp[1];
disp[0]= offsetof(union atributo, valor2);  
MPI_Type_create_struct(1, blocklen, disp, type, &atributo_MPI);
MPI_Type_commit(&atributo_MPI);



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

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

MPI_Type_create_struct(2, blocklen2, disp2, type2, &estructura_MPI);
MPI_Type_commit(&estructura_MPI);   

这是我如何发送 3 种 union 的示例。

union atributo *atributo2;
atributo2=malloc(sizeof(char) * (tamChar+1));
atributo2[0].valor1= 99999999;
MPI_Send(&atributo2[0], 1, atributo_MPI, 1, 123, MPI_COMM_WORLD);


union atributo *atributo3;
atributo3=malloc(sizeof(char) * (tamChar+1));   
for(k=0;k<tamChar;k++){
    atributo3[0].valor2[k]= 'A' + ( rand() % ( 'Z' - 'A')); 
}
atributo3[0].valor2[k] = '\0';
MPI_Send(&atributo3[0], 1, atributo_MPI, 2, 123, MPI_COMM_WORLD);



union atributo *atributo4;
atributo4=malloc(sizeof(char) * (tamChar+1));
float valor1,valor2;
srand(rdtsc());

valor1=(((float)rand())+1.0)*500000.0;
valor2=(((float)rand())+1.0)*25.0;
atributo4[0].valor3=valor2/valor1;

MPI_Send(&atributo4[0], 1, atributo_MPI, 3, 123, MPI_COMM_WORLD);

这里接收:

union atributo *atributo3;
atributo3=malloc(sizeof(char) * (tamChar+1));
MPI_Recv(&atributo3[0],1,atributo_MPI,0,MPI_ANY_TAG,MPI_COMM_WORLD,&status);    
printf("Valor atributo CHAR %s\n",atributo3[0].valor2);   // HERE IT CRASH

如果我尝试发送 UNION,它可以很好地处理 float 和 int,但不能处理 char 数组。

这是我尝试打印 value2 时的错误:

*** Process received signal ***
Signal: Segmentation fault (11)
Signal code: Address not mapped (1)
Failing at address: 0x7fa02e917678

当然,该结构还没有工作。 我将不胜感激任何答案。 谢谢。

最佳答案

本质上,指针是内存中的一个地址。每个 MPI 进程都有自己的地址空间,这是使它们成为进程的一部分。指向一个进程空间中地址的指针在另一个进程空间中是无用的。

无法保证两个不同的 MPI 进程在其内存空间中具有相同的地址集。

即使它们确实具有相同的地址空间,也没有隐含的保证,也没有任何方式保证两个对象,其中一个包含指向另一个的指针,将以这种方式从一个进程发送到另一个进程原始地址空间中的指针指向接收地址空间中的另一个对象。

如果您需要将带有指针的结构从一个进程发送到另一个进程,您将必须发送足够的信息以使接收进程能够在其自己的地址空间中建立自己的指针。

另见 MPI send derived data type with pointer in Fortran 90

关于c - MPI 上带有指针的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19824141/

相关文章:

c++ - 打印文件的创建时间为什么是+7 :00 hours ahead of the actual file creation time?

c++ - 在 char 字符串数组上应用 c++ "lower_bound"

c - 如何使用c在链表节点中传递两个参数?

c - 如何使用 C(不是 C++)在结构的所有实例中拥有一个 const 成员?

创建 scanf 以格式化文本文件

c - C语言删除数组中多个元素的算法

c - 一个整数有多大?

c++ - 填充指向 vector 的指针 vector 会产生奇怪的结果

c++ - 将本地对象转换为指针,而不复制数据?

c - 在C中使用函数将值放入结构中