Skip to content

Instantly share code, notes, and snippets.

@lorenzhs
Created August 26, 2015 09:14
Show Gist options
  • Save lorenzhs/79dab54552fd1f9381da to your computer and use it in GitHub Desktop.
Save lorenzhs/79dab54552fd1f9381da to your computer and use it in GitHub Desktop.
#include <boost/mpi.hpp>
/*
* Example how boost::mpi::broadcast could be implemented efficiently for types
* that need to be serialized, without falling back to Point-to-Point communication
*
* Lorenz Hübschle-Schneider, 2015
* Distributed under the Boost Software License, Version 1.0
*/
template <typename T>
void broadcast(const boost::mpi::communicator &comm, std::vector<T> &data, int root) {
if (comm.size() < 2) return;
if (boost::mpi::is_mpi_datatype<T>()) {
// Use existing behaviour
boost::mpi::broadcast(comm, data, root);
} else {
// Boost.MPI doesn't use MPI_Bcast for types it doesn't know.
// Therefore, we need to do the archive broadcast ourselves.
if (comm.rank() == root) {
// Serialize data
boost:mpi::packed_oarchive oa(comm);
oa << data;
// Broadcast archive size
size_t archive_size = oa.size();
boost:mpi::broadcast<size_t>(comm, archive_size, root);
// Broadcast archive data
auto sendptr = const_cast<void*>(oa.address());
MPI_Bcast(sendptr, archive_size, MPI_PACKED, root, comm);
} else {
// Receive archive size and allocate space
size_t archive_size;
boost::mpi::broadcast<size_t>(comm, archive_size, root);
boost::mpi::packed_iarchive ia(comm);
ia.resize(archive_size);
// Receive broadcast archive data
auto recvptr = ia.address();
MPI_Bcast(recvptr, archive_size, MPI_PACKED, root, comm);
// Unpack received data
ia >> data;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment