After I broadcast my final array in rank 0 to all other nodes. It should then back to the loop and all of the nodes have the same array. But in fact, I got the original array instead of the array after broadcasting. I am using MPI to do it. I am sure how to use loop in MPI. I have a program similar to this one. First, I need to deal with some calculation with the array in each node. Then find one array among nodes that I need, then I repeat the step from the beginning and do it again and again. Can anyone help me with it or give me better ways to do it? Thank you to everyone.
int main(int argc, char** argv) {
//set array of long double to send
long double array[4][4]{0}, compenergy=0;
int size, rank;
int i, j;
int rank_lowest_energy, lowrank;
MPI_Status status;
struct {
long double val;
int rank;
} energy, lowenergy;
lowenergy.val = 0;
MPI_Init(NULL, NULL);
// Get the number of processes
size = MPI::COMM_WORLD.Get_size();
// Get the rank of the process
rank = MPI::COMM_WORLD.Get_rank();
for (int m = 0; m < 3; ++m)
{
//MPI::COMM_WORLD.Bcast(&array, 4*4, MPI::LONG_DOUBLE, 0);
if (rank == 0)
{
energy.val = 10000;
energy.rank = rank;
}
else
{
for (i = 0; i < rank; ++i)
array[rank][i] += rank;
energy.val = rank + 10 - array[rank][0]- lowenergy.val;
energy.rank = rank;
}
MPI_Allreduce(&energy, &lowenergy, 1, MPI_LONG_DOUBLE_INT, MPI_MINLOC, MPI_COMM_WORLD);
if (rank == lowenergy.rank)
MPI::COMM_WORLD.Send(&array, 4 * 4, MPI::LONG_DOUBLE, 0, 0);
if (rank == 0)
{
MPI::COMM_WORLD.Recv(&array, 4 * 4, MPI::LONG_DOUBLE, MPI::ANY_SOURCE, MPI::ANY_TAG);
cout << "Its rank is: " << lowenergy.rank << "\n";
cout<< "Its value is: "<<lowenergy.val<<"\n";
for (i = 0; i < 4; ++i)
{
for (j = 0; j < 4; ++j)
cout << array[i][j] << " ";
cout << "\n";
}
MPI::COMM_WORLD.Bcast(&lowenergy, 1, MPI::LONG_DOUBLE_INT, 0);
}
MPI::COMM_WORLD.Bcast(&array, 4*4, MPI::LONG_DOUBLE, 0);
}
MPI::Finalize();
}