使用MPI子数组发送3D数组块

时间:2019-01-26 11:46:12

标签: c arrays mpi sub-array

我是MPI的新手,我正在尝试学习如何使用MPI_Type_create_subarray以便将其应用到我的项目中。 我花了很多时间寻找适合我需要的教程,但是没有成功。

因此,我尝试将How to use MPI_Type_create_subarray 中的概念推广到3D阵列,但是仍然缺少某些东西。

尤其是当我尝试查看结果时,我的代码返回了Segmentation Fault error或显示了错误的数据。 我不明白我在哪里弄错了

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>

void printarr(int ***data, int nx, int ny, int nz, char *str);
int ***allocarray(int nx, int ny, int nz);

int main(int argc, char **argv) {

/* array sizes */
const int bigsize =10;
const int subsize_x =2;      const int subsize_y =2;     const int subsize_z =2;

/* communications parameters */
const int sender  =0;
const int receiver=1;
const int ourtag  =2;

int rank, size;

MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);

if (size < receiver+1) {
    if (rank == 0)
        fprintf(stderr,"%s: Needs at least %d  processors.\n", argv[0], receiver+1);
    MPI_Finalize();
    return 1;
}


MPI_Datatype mysubarray;

int starts[3] = {0,0,0};
int subsizes[3]  = {subsize_x,subsize_y,subsize_z};
int bigsizes[3]  = {bigsize, bigsize, 3};
MPI_Type_create_subarray(3, bigsizes, subsizes, starts, MPI_ORDER_C, MPI_INT, &mysubarray);
MPI_Type_commit(&mysubarray);

if (rank == sender) {
    int ***bigarray = allocarray(bigsize,bigsize,3);
    for (int k=0; k<3; k++)
        for (int j=0; j<bigsize; j++)
            for(int i=0; i< bigsize; i++) {
                bigarray[k][j][i] = k*(bigsize*bigsize)+j*bigsize+i;
            }

    printarr(bigarray, bigsize, bigsize, 3, " Sender: Big array ");

    MPI_Send(&(bigarray[0][0][0]), 1, mysubarray, receiver, ourtag, MPI_COMM_WORLD);
    MPI_Type_free(&mysubarray);

    free(bigarray);

} else if (rank == receiver) {

    int ***subarray = allocarray(subsize_x,subsize_y,subsize_z);
    MPI_Recv(&(subarray[0][0][0]), subsizes[0]*subsizes[1]*subsizes[2], MPI_INT, sender, ourtag, MPI_COMM_WORLD, MPI_STATUS_IGNORE);

    printarr(subarray, subsize_x, subsize_y, subsize_z, " Receiver: Subarray -- after receive");

    free(subarray);
}

MPI_Finalize();
return 0;
}

void printarr(int ***data, int nx, int ny, int nz, char *str) {
printf("-- %s --\n", str);
for(int k=0; k<nz; k++) {
    printf("\n\n-----%d------\n",k);
    for (int j=0; j<ny;j++) {
        for (int i=0; i<nx; i++) {
            printf("%3d ", data[k][j][i]);
        }
    printf("\n");
    }
}
}

int ***allocarray(int nx, int ny, int nz) {

int*** arr = (int***)malloc(sizeof(int**)*nz);
for(int k = 0; k < nz; k++) {
    arr[k]= (int**)malloc(sizeof(int*)*ny);
    for(int j = 0; j< ny; j++){
        arr[k][j] = (int*)malloc(sizeof(int)*nx);
        for(int i = 0; i < nx; i++){
            arr[k][j][i] = 0;
        }
    }
}
return arr;
}

0 个答案:

没有答案