Sending the size of the array is redundant (and inefficient) because MPI provides a way to search for incoming messages without receiving them, which provides enough information for the correct memory allocation. The study is performed with help MPI_PROBEthat is very similar to MPI_RECV, except that it does not accept buffer related arguments. The probe operation returns a state object that can then be queried for the number of elements of a given MPI data type that can be retrieved from the contents of the message using MPI_GET_COUNT, so explicitly sending the number of elements becomes unnecessary.
Here is a simple example with two ranks:
if (rank == 0)
{
MPI_Request req;
MPI_Isend(arr1, n, MPI_DOUBLE, 1, 0, MPI_COMM_WORLD, &req);
MPI_Wait(&req, MPI_STATUS_IGNORE);
}
else if (rank == 1)
{
MPI_Status status;
MPI_Probe(0, 0, MPI_COMM_WORLD, &status);
MPI_Get_count(&status, MPI_DOUBLE, &n);
arr1 = malloc(n*sizeof(double));
MPI_Recv(arr1, n, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
MPI_PROBE MPI_ANY_SOURCE MPI_ANY_TAG. , .
, , . , , . . .