I am trying to broadcast a value from a root process and receive it in all other processes. I have implemented it in the following two formats. 1. I used broadcast function in all processes (root and all other slaves)
#include <boost/mpi.hpp>
#include <iostream>
#include <boost/serialization/string.hpp>
namespace mpi = boost::mpi;
int main(int argc, char* argv[])
{
mpi::environment env(argc, argv);
mpi::communicator world;
std::string value;
if (world.rank() == 0) {
value = "Hello, World!";
}
broadcast(world, value, 0);
std::cout << "Process #" << world.rank() << " says " << value << std::endl;
return 0;
}
2. I call broadcast only from root while call receive from other processes as follows:
if (world.rank() == 0) {
value = "Hello, World!";
broadcast(world, value, 0);
}
else {
world.recv(boost::mpi::any_source, boost::mpi::any_tag, value);
}
both seem to work similar in these examples, but I want to know if there is any preferences in terms of code efficiency and performance here.
Thank you!
Use the plain broadcast
.
The second version is not a correct MPI program. If it works, it is only by chance. In general broadcast
and the other collectives are highly optimized and can utilize system topology information. Thus they perform better than if you would implement it on your own using point-to-point messages. Also they express your communication structure in a more abstract way, resulting in cleaner code.