#include #include #include #include #include #include #include namespace mpi = boost::mpi; /// A very simple MPI message class hello_msg { int rank_; std::string node_; std::string os_; public: /// Ctor, using mpi::communicator instance to get rank no. hello_msg(const mpi::communicator& comm) { rank_ = comm.rank(); // get nodename and os from uname(2) struct utsname uname_; uname(&uname_); node_ = uname_.nodename; os_ = uname_.sysname; }; /// Default ctor, to use only just before serialization hello_msg() : rank_(-1), node_("unknown"), os_("unknown") { }; // print out the greeeting friend std::ostream& operator<< (std::ostream& o, hello_msg const& msg) { o << "Hello from MPI rank " << msg.rank_ << " running on host " << msg.node_ << " (" << msg.os_ <<")" << std::endl; }; protected: // provide serialization of this class, for MPI send/recv friend class boost::serialization::access; template void serialize(Archive& ar, const unsigned int version) { ar & rank_ & node_ & os_; }; }; int main(int argc, char** argv) { mpi::environment env(argc, argv); mpi::communicator world; // every MPI rank creates an "hello_msg" instance... hello_msg hello(world); // ...and sends it to rank 0 world.send(0, 0, hello); // rank 0 prints out messages in the order they are received if (0 == world.rank()) { unsigned int n = world.size(); while (n > 0) { mpi::status msg = world.probe(); hello_msg greeting; world.recv(msg.source(), msg.tag(), greeting); std::cout << greeting; --n; }; }; return 0; }