ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
Loading...
Searching...
No Matches
reduce_optional.hpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2022 The ESPResSo project
3 *
4 * This file is part of ESPResSo.
5 *
6 * ESPResSo is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * ESPResSo is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19#ifndef UTILS_MPI_REDUCE_OPTIONAL_HPP
20#define UTILS_MPI_REDUCE_OPTIONAL_HPP
21
22#include <boost/mpi/collectives/all_reduce.hpp>
23#include <boost/mpi/communicator.hpp>
24
25#include <cassert>
26#include <functional>
27#include <optional>
28
29namespace Utils::Mpi {
30
31/**
32 * @brief Reduce an optional on the head node.
33 * Worker nodes get a default-constructed object.
34 */
35template <typename T>
36T reduce_optional(boost::mpi::communicator const &comm,
37 std::optional<T> const &result) {
38 assert(1 == boost::mpi::all_reduce(comm, static_cast<int>(!!result),
39 std::plus<>()) &&
40 "Incorrect number of return values");
41 if (comm.rank() == 0) {
42 if (result) {
43 return *result;
44 }
45 T value;
46 comm.recv(boost::mpi::any_source, 42, value);
47 return value;
48 }
49 if (result) {
50 comm.send(0, 42, *result);
51 }
52 return {};
53}
54
55} // namespace Utils::Mpi
56
57#endif
T reduce_optional(boost::mpi::communicator const &comm, std::optional< T > const &result)
Reduce an optional on the head node.