【问题标题】:How to create new Type in MPI如何在 MPI 中创建新类型
【发布时间】:2013-12-01 04:23:09
【问题描述】:

我是 MPI 的新手,我想为 Residence struct 创建一个新的数据类型。我只是想看看我是否可以正确地创建新类型。 结构住宅 { 双x; 双 y; };

我的新 MPI 类型

MPI_Datatype createRecType()
{
    // Set-up the arguments for the type constructor
    MPI_Datatype new_type;

    int count = 2;
    int blocklens[] = { 1,1 };

    MPI_Aint indices[2];
    //indices[0]=0;
    MPI_Type_extent( MPI_DOUBLE, &indices[0] );
    MPI_Type_extent( MPI_DOUBLE, &indices[1] );

    MPI_Datatype old_types[] = {MPI_DOUBLE,MPI_DOUBLE};

    MPI_Type_struct(count,blocklens,indices,old_types,&new_type);
    MPI_Type_commit(&new_type);

}

【问题讨论】:

    标签: c++ c mpi cluster-computing mpich


    【解决方案1】:

    除了indices 应该给出每个结构字段从结构的开始 开始的字节偏移量之外,您几乎做对了。构造这种类型的正确方法是使用offsetof 运算符,在stddef.h 中定义:

    #include <stddef.h>  // or <cstddef> for C++
    
    struct Residence
    {
       double x;
       double y;
    };
    
    MPI_Datatype createRecType()
    {
        // Set-up the arguments for the type constructor
        MPI_Datatype new_type;
    
        int count = 2;
        int blocklens[] = { 1,1 };
    
        MPI_Aint indices[2];
        indices[0] = (MPI_Aint)offsetof(struct Residence, x);
        indices[1] = (MPI_Aint)offsetof(struct Residence, y);
    
        MPI_Datatype old_types[] = {MPI_DOUBLE,MPI_DOUBLE};
    
        MPI_Type_struct(count,blocklens,indices,old_types,&new_type);
        MPI_Type_commit(&new_type);
    
        return new_type;
    }
    

    虽然这对于该特定结构就足够了,但通常必须调整结构化类型长度,以考虑编译器可能在结构末尾插入的任何尾随填充。仅当想要发送该结构化类型的多个项目时才需要这样做,即结构元素的数组。旧的方法是在MPI_UB 类型的结构中添加第三个成员(UB 来自Upper Bound)并将该成员的偏移量设置为等于sizeof(struct Residence)(填充在结构大小中计算为由sizeof 返回)。现代的方法是使用MPI_Type_create_resized,它创建一个新的MPI类型,其类型签名与原始类型签名相同,但程度不同:

        MPI_Type_struct(count,blocklens,indices,old_types,&new_type);
        // Create a resized type
        MPI_Type resized_new_type;
        MPI_Type_create_resized(new_type,
                                // lower bound == min(indices) == indices[0]
                                indices[0],
                                (MPI_Aint)sizeof(struct Residence),
                                &resized_new_type);
        MPI_Type_commit(&resized_new_type);
        // Free new_type as it is no longer needed
        MPI_Type_free(&new_type);
    
        return resized_new_type;
    

    仅显示相关的代码行。上面的代码假设indices[0] 给出了第一个结构元素的偏移量。可以改为使用MPI_Type_get_extent 来获得真正的下限,这适用于具有负偏移量的结构类型。不必提交new_type,因为它仅用于构造调整大小的类型。也没有必要保留它,这就是为什么在创建 resized_new_type 之后释放它。

    【讨论】:

      猜你喜欢
      • 2013-12-02
      • 2021-02-05
      • 2019-03-29
      • 1970-01-01
      • 2021-03-22
      • 2021-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多