Ticket #6704: allreduce.cpp

File allreduce.cpp, 1.1 KB (added by Alain Miniussi <alain.miniussi@…>, 11 years ago)

c++ source code

Line 
1#include <iostream>
2#include <vector>
3#include <algorithm>
4
5#include "boost/mpi.hpp"
6
7int main(int argc, char* argv[]) {
8 namespace mpi = boost::mpi;
9 mpi::environment env(argc, argv);
10 mpi::communicator world;
11 std::vector<int> in(10, world.rank());
12 std::vector<int> out(10, 0);
13 std::vector<int>& sendbuf = argc == 1 ? in : out;
14
15 mpi::all_reduce(world, &(sendbuf[0]), sendbuf.size(), &(out[0]), std::plus<int>());
16 int result = 0;
17 for (int i = 0; i < world.size(); ++i) {
18 result += i;
19 }
20 for (int i = 0; i < world.size(); ++i) {
21 world.barrier();
22 if (i == world.rank()) {
23 std::cout << "This is P" << i;
24 if (std::equal_range(out.begin(), out.end(), result)
25 == std::make_pair(out.begin(), out.end())) {
26 std::cout << " good\n";
27 } else {
28 std::cout << " bad ->";
29 std::copy(out.begin(), out.end(),
30 std::ostream_iterator<int>(std::cout, " "));
31 std:: cout << " instead of " << result << '\n';
32 }
33 }
34 }
35 return 0;
36}