如何使用MPI_Isend发送多维,动态和增长的数组

时间:2015-09-06 11:32:45

标签: c arrays parallel-processing malloc mpi

我创建了一个数组,我想用MPI发送它。第一部分运作良好(我认为?)但我的第二部分有问题。我想这是接收部分以及我如何malloc数组? 请看一下:

if (myrank > 1)
{
    //first part
    int rows = 5;
    int cols = 4;
    int realcount = 0;
    int (*sendarray)[cols] = malloc(sizeof *sendarray * rows);
    for (int j = 0; j < 100; ++j)
    {
        for (int k = 0; k < 100; ++k)
        {
            for (int l = 0; l < 100; ++l)
            {
                if(realcount==rows){
                    int newnum = (rows + 2) * 2;
                    int (*newptr)[cols] = realloc(sendarray, sizeof *newptr * newnum);
                    rows = newnum;
                    sendarray = newptr;
                }
                /*
                    other stuff and checks
                */
                if(checks)
                {
                    sendarray[realcount][0] = j;
                    sendarray[realcount][1] = k;
                    sendarray[realcount][2] = l;
                    sendarray[realcount][3] = max;
                    ++realcount;
                }
            }
        }
    }
    //Send array
    MPI_Request req;
    MPI_Isend(sendarray, realcount, MPI_INT, 1, 1, MPI_COMM_WORLD, &req);
    MPI_Wait(&req, MPI_STATUS_IGNORE);
}else if(myrank == 1){
    //second part
    //for-loop: check incomming data for each task > 1
    for () {
        i = task thats going to send data
        int amount = 0;
        int cols = 4;
        MPI_Status status;
        MPI_Probe(i, 1, MPI_COMM_WORLD, &status);
        MPI_Get_count(&status, MPI_INT, &amount);
        int (*recv_buf)[cols] = malloc(sizeof *recv_buf * amount);
        MPI_Recv(recv_buf, amount, MPI_INT, i, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        for (int var = 0; var < amount; ++var) {
            //wrong data here
            fprintf(fp, "{ \"x\": %d, \"y\": %d, \"z\": %d, \"value\": %d },", recv_buf[var][0], recv_buf[var][1], recv_buf[var][2], recv_buf[var][3]);
        }
        free(recv_buf);
    }
}

非常感谢你的帮助。 我看了https://stackoverflow.com/a/13535563/2521647https://stackoverflow.com/a/14051503/2521647

1 个答案:

答案 0 :(得分:1)

你告诉MPI发送和接收许多MPI_INTs,但你的数据实际上是4 MPI_INT。

我不知道这是否是唯一的问题,但这可以解释为什么你得到的阵列不同于你预期的填充。

编辑:在您的情况下,您需要执行以下操作:

MPI_Isend(sendarray, realcount*cols, MPI_INT, 1, 1, MPI_COMM_WORLD, &req);

     int (*recv_buf)[cols] = malloc(sizeof *recv_buf * amount/4);
     ...
     for (int var = 0; var < amount/4; ++var) {

或使用derived datatype来描述您要发送的4个整数。