I am working on a simple program in C++ that uses MPI to communicate between two processes. If I want to send an array to another process, the MPI_Send
and MPI_Recv
functions expect a pointer to the said array:
int MPI_Send(void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm)
int MPI_Recv(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Status *status);
In an online tutorial I saw the following usage of MPI_Send and MPI_Recv:
int values[5] = {1, 2, 3, 4, 5};
MPI_Send(values, 5, MPI_INT, 1, 0, MPI_COMM_WORLD);
and
int values[10];
MPI_Recv(&values, 10, MPI_INT, 3, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
Why does the tutorial use in one case only values
and in the other case also the address operator &values
?
I wrote a program to send and receive arrays between two processes and it seems that it works with and without the address operator. Why is this the case? I'm certainly mistaken in my thinking. Can you help me find my mistake?
Here is my code:
#include <iostream>
#include <mpi.h>
int main(int argc, char** argv) {
MPI_Init(&argc, &argv);
// Reading size and rank
int size, rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// For every process create array
double array[2];
if (rank == 0) {
array[0] = 0.1;
array[1] = 0.2;
} else {
if (rank == 1) {
array[0] = 1.1;
array[1] = 1.2;
}
}
// Send and receive
double other_array[2];
if (rank == 0) {
MPI_Send(&array, 2, MPI_DOUBLE, 1, 99, MPI_COMM_WORLD);
MPI_Recv(&other_array, 2, MPI_DOUBLE, 1, 99, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
// OR
// MPI_Send(array, 2, MPI_DOUBLE, 1, 99, MPI_COMM_WORLD);
// MPI_Recv(other_array, 2, MPI_DOUBLE, 1, 99, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
std::cout << rank << " " << other_array[0] << " " << other_array[1] << std::endl;
} else {
MPI_Recv(&other_array, 2, MPI_DOUBLE, 0, 99, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
MPI_Send(&array, 2, MPI_DOUBLE, 0, 99, MPI_COMM_WORLD);
// OR
// MPI_Recv(other_array, 2, MPI_DOUBLE, 0, 99, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
// MPI_Send(array, 2, MPI_DOUBLE, 0, 99, MPI_COMM_WORLD);
std::cout << rank << " " << other_array[0] << " " << other_array[1] << std::endl;
}
// Finalisation
int MPI_Finalize();
return 0;
}
I compiled and ran the programm using
mpic++ -O -Wall main.cpp -o main
mpirun -np 2 ./main