结构体类型的创建(数组结构体)
#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
struct Value{
int a;
double b;
};
void initArray(struct Value *array, int size)
{
for (int i = 0; i < size; i++)
{
array[i].a = (int)(rand() % 10 + 1);
array[i].b = (double)(rand() % 10 + 1);
}
}
void printArray(const char *name,struct Value *array, int ranknode, int size)
{
printf("%s rank%d\n", name, ranknode);
for (int i = 0; i < size; i++)
{
printf("i=%d a=%d,b=%lf\n", i, array[i].a, array[i].b);
}
printf("\n");
}
int main(int argc, char *argv[])
{
int structSize=2;
int rank;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Datatype mystruct;
int blocklens[2];
MPI_Aint indices[2];
MPI_Datatype old_types[2];
struct Value value;
blocklens[0] = 1;
blocklens[1] = 1;
old_types[0] = MPI_INT;
old_types[1] = MPI_DOUBLE;
MPI_Get_address(&value.a, &indices[0]);
MPI_Get_address(&value.b, &indices[1]);
indices[1] = indices[1]-indices[0];
indices[0] = 0;
MPI_Type_create_struct(2, blocklens, indices, old_types, &mystruct);
MPI_Type_commit(&mystruct);
//MPI_Type_get_extent 该函数以字节为单位返回指定数据类型的跨度extent
//MPI_Type_size 该函数以字节为单位返回指定数据类型的有用部分的大小,即跨度减去类型中的空隙。
MPI_Aint lb,extent;
MPI_Type_get_extent(mystruct,&lb, &extent);
int size;
MPI_Type_size(mystruct, &size);
struct Value *pt = (struct Value *)malloc(structSize * sizeof(struct Value));
if (0==rank) {
printf("double stride: %d\n",(int)indices[1]);
printf("MPI_Type_get_extent length:%d\n",(int)extent);
printf("MPI_Type_get_extent min: %d\n",(int)lb);
printf("size of struct: %d\n",(int)sizeof(value));
printf("MPI_Type_size: %d\n", size);
initArray(pt, structSize);
printf("\nrank0 打印 ");
printArray("struct", pt,rank, structSize);
}
MPI_Bcast(pt, structSize, mystruct, 0, MPI_COMM_WORLD);
printArray("struct", pt,rank, structSize);
MPI_Type_free(&mystruct);
free(pt);
MPI_Finalize();
}
结构体内元素的偏移
将各种数据类型放在地址为8的倍数的存储空间内
MPI_Type_get_extent 该函数以字节为单位返回指定数据类型的跨度extent。
MPI_Type_size 该函数以字节为单位返回指定数据类型的有用部分的大小,即跨度减去类型中的空隙。
结构体数据类型
MPI_Type_struct (已弃用)
MPI_Type_struct (count,blocklens[],offsets[],old_types,*newtype) :
最通用的类型构造函数,多种类型的MPI_Type_indexed
MPI_Type_create_struct(新)
MPI_Type_create_struct(count, array_of_blocklengths[], array_of_displacements[], array_of_types[],*rowtype);
数据类型长度
MPI_Type_extent (已弃用)
MPI_Type_extent (datatype,*extent) : extent返回数据类型长度
MPI_Type_get_extent(新)
MPI_Type_get_extent(rowtype, *lb, *extent) : lb返回最小数据类型长度,extent返回数据类型长度