我创建了一个数组,我想用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/2521647和https://stackoverflow.com/a/14051503/2521647
您告诉MPI发送和接收realcount许多mpi_int,但您的数据实际上是4个mpi_int。
我不知道这是否是唯一的问题,但这可以解释,为什么你得到一个不同的填充你的数组比你期望的。
edit:在您的情况下,您需要这样做:
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) {
或使用派生数据类型来描述要发送的4个整数