gpt4 book ai didi

c++ - 段错误 : Struct Serialisation and MPI Data Transfer in C++

转载 作者:行者123 更新时间:2023-11-30 04:46:51 25 4
gpt4 key购买 nike

我正在尝试将序列化结构从一个等级发送到另一个等级。结果是

Segmentation fault: 11

我不知道它来自哪里。

我试图通过打印出一些值来定位问题,并且代码总是在 MPI_SendMPI_Recv 之间中断,但由于它是段错误,因此无法确定这是问题的根源。请赐教。

int N = 11;
struct tests{
int number;
double *fx;
};

void locateMemoryTests(struct tests *t){
t->fx = (double*) malloc(N*sizeof(double));
}

void he(struct tests *t, int N){
int NRank, MyRank;
MPI_Comm_rank( MPI_COMM_WORLD, &MyRank );
MPI_Comm_size( MPI_COMM_WORLD, &NRank );
int st = MyRank * int(N/2);
int en = (MyRank+1) * int(N/2) + (N%2)*MyRank;

for (int i=st; i<en; i++){
t->fx[i] = i*i + 5*(i + t->number);
}
const int nitems = 2;
int blocklengths[2] = {1, N};
MPI_Datatype types[2] = {MPI_INT, MPI_DOUBLE};
MPI_Datatype mpi_tests_type;
MPI_Aint offsets[2];

offsets[0] = offsetof(tests, number);
offsets[1] = offsetof(tests, fx);

MPI_Type_create_struct(nitems, blocklengths, offsets, types, &mpi_tests_type);
MPI_Type_commit(&mpi_tests_type);
MPI_Comm_rank(MPI_COMM_WORLD, &MyRank);

if (MyRank == 0){
struct tests send;
send.number = t->number;
locateMemoryTests(&send);

for (int i=0; i<N; i++){
send.fx[i] = t->fx[i];
}

MPI_Send(&send, 2, mpi_tests_type, 1, 111, MPI_COMM_WORLD);
}
else if (MyRank == 1){
MPI_Status status;
struct tests recv;
locateMemoryTests(&recv);
MPI_Recv(&recv, 2, mpi_tests_type, 0, 111, MPI_COMM_WORLD, &status);

MPI_Type_free(&mpi_tests_type);
}


int main( int argc, char *argv[] ){
int NRank, MyRank;
MPI_Init( &argc, &argv );
MPI_Comm_rank( MPI_COMM_WORLD, &MyRank );
MPI_Comm_size( MPI_COMM_WORLD, &NRank );

struct tests tt;
tt.number = 5;
locateMemoryTests(&tt);

he(&tt,N);

MPI_Finalize();
return 0;
}

最佳答案

您的 MPI 派生数据类型描述了以下 C struct

struct tests{
int number;
double fx[N];
};

但是你用的是不同的

struct tests{
int number;
double *fx;
};

如果 N 不是常量,您可以声明

struct tests{
int number;
double fx[];
};

正确分配这样的结构取决于您。

另一种选择是保持相同的struct 定义,并手动MPI_Pack()MPI_Unpack() 将数据传入/传出临时缓冲区。

关于c++ - 段错误 : Struct Serialisation and MPI Data Transfer in C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56507811/

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