#include <iostream>
#include <mpi.h>
int main(int argc, char *argv[])
{
int nitems = 10;
int mynode, totalnodes;
MPI_Status status;
double *array;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &totalnodes);
MPI_Comm_rank(MPI_COMM_WORLD, &mynode);
array = new double[nitems];
if (mynode == 0)
{
// Initialize array only on the root node
for (int i = 0; i < nitems; i++)
array[i] = (double)i;
}
if (mynode == 0)
{
// Send array to each other process once
for (int i = 1; i < totalnodes; i++)
{
MPI_Send(array, nitems, MPI_DOUBLE, i, 1, MPI_COMM_WORLD);
}
}
else
{
// Each non-root process receives the array only once
MPI_Recv(array, nitems, MPI_DOUBLE, 0, 1, MPI_COMM_WORLD, &status);
}
// Print array on each processor
for (int i = 0; i < nitems; i++)
{
printf("Processor %d: array[%d] = %f\n", mynode
, i
, array
[i
]); }
delete[] array;
MPI_Finalize();
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8bXBpLmg+CgppbnQgbWFpbihpbnQgYXJnYywgY2hhciAqYXJndltdKQp7CiAgICBpbnQgbml0ZW1zID0gMTA7CiAgICBpbnQgbXlub2RlLCB0b3RhbG5vZGVzOwogICAgTVBJX1N0YXR1cyBzdGF0dXM7CiAgICBkb3VibGUgKmFycmF5OwoKICAgIE1QSV9Jbml0KCZhcmdjLCAmYXJndik7CiAgICBNUElfQ29tbV9zaXplKE1QSV9DT01NX1dPUkxELCAmdG90YWxub2Rlcyk7CiAgICBNUElfQ29tbV9yYW5rKE1QSV9DT01NX1dPUkxELCAmbXlub2RlKTsKCiAgICBhcnJheSA9IG5ldyBkb3VibGVbbml0ZW1zXTsKCiAgICBpZiAobXlub2RlID09IDApCiAgICB7CiAgICAgICAgLy8gSW5pdGlhbGl6ZSBhcnJheSBvbmx5IG9uIHRoZSByb290IG5vZGUKICAgICAgICBmb3IgKGludCBpID0gMDsgaSA8IG5pdGVtczsgaSsrKQogICAgICAgICAgICBhcnJheVtpXSA9IChkb3VibGUpaTsKICAgIH0KCiAgICBpZiAobXlub2RlID09IDApCiAgICB7CiAgICAgICAgLy8gU2VuZCBhcnJheSB0byBlYWNoIG90aGVyIHByb2Nlc3Mgb25jZQogICAgICAgIGZvciAoaW50IGkgPSAxOyBpIDwgdG90YWxub2RlczsgaSsrKQogICAgICAgIHsKICAgICAgICAgICAgTVBJX1NlbmQoYXJyYXksIG5pdGVtcywgTVBJX0RPVUJMRSwgaSwgMSwgTVBJX0NPTU1fV09STEQpOwogICAgICAgIH0KICAgIH0KICAgIGVsc2UKICAgIHsKICAgICAgICAvLyBFYWNoIG5vbi1yb290IHByb2Nlc3MgcmVjZWl2ZXMgdGhlIGFycmF5IG9ubHkgb25jZQogICAgICAgIE1QSV9SZWN2KGFycmF5LCBuaXRlbXMsIE1QSV9ET1VCTEUsIDAsIDEsIE1QSV9DT01NX1dPUkxELCAmc3RhdHVzKTsKICAgIH0KCiAgICAvLyBQcmludCBhcnJheSBvbiBlYWNoIHByb2Nlc3NvcgogICAgZm9yIChpbnQgaSA9IDA7IGkgPCBuaXRlbXM7IGkrKykKICAgIHsKICAgICAgICBwcmludGYoIlByb2Nlc3NvciAlZDogYXJyYXlbJWRdID0gJWZcbiIsIG15bm9kZSwgaSwgYXJyYXlbaV0pOwogICAgfQoKICAgIGRlbGV0ZVtdIGFycmF5OwogICAgTVBJX0ZpbmFsaXplKCk7CiAgICByZXR1cm4gMDsKfQ==