|
2 | 2 |
|
3 | 3 | [TOC] |
4 | 4 |
|
5 | | -In this example, we show how to register a new MPI datatype and how to use mpi::map_C_function and mpi::map_add to |
6 | | -define MPI operations for it. |
| 5 | +In this example, we show |
| 6 | +- how to register a new MPI datatype by providing a `tie_data` function for our C++ type and |
| 7 | +- how to use mpi::map_C_function and mpi::map_add to define MPI operations for it. |
7 | 8 |
|
8 | | -```cpp |
9 | | -#include <mpi/mpi.hpp> |
10 | | -#include <iostream> |
11 | | - |
12 | | -// define a custom complex type |
13 | | -struct my_complex { |
14 | | - double real; |
15 | | - double imag; |
16 | | -}; |
17 | | - |
18 | | -// define an addition for my_complex |
19 | | -inline my_complex operator+(const my_complex& z1, const my_complex& z2) { |
20 | | - return { z1.real + z2.real, z1.imag + z2.imag }; |
21 | | -} |
22 | | - |
23 | | -// define a tie_data function for my_complex to make it MPI compatible |
24 | | -inline auto tie_data(const my_complex& z) { |
25 | | - return std::tie(z.real, z.imag); |
26 | | -} |
27 | | - |
28 | | -int main(int argc, char *argv[]) { |
29 | | - // initialize MPI environment |
30 | | - mpi::environment env(argc, argv); |
31 | | - mpi::communicator world; |
32 | | - |
33 | | - // create complex number z |
34 | | - my_complex z = { world.rank() + 1.0, static_cast<double>(world.rank()) }; |
35 | | - |
36 | | - // sum z over all processes |
37 | | - auto sum = mpi::reduce(z, world, 0, false, mpi::map_add<my_complex>()); |
38 | | - |
39 | | - // define a product for my_complex |
40 | | - auto my_product = [](const my_complex& z1, const my_complex& z2) { |
41 | | - return my_complex { z1.real * z2.real - z1.imag * z2.imag, z1.real * z2.imag + z1.imag * z2.real }; |
42 | | - }; |
43 | | - |
44 | | - // multiply z over all processes |
45 | | - auto product = mpi::reduce(z, world, 0, false, mpi::map_C_function<my_complex, my_product>()); |
46 | | - |
47 | | - // print result |
48 | | - if (world.rank() == 0) { |
49 | | - std::cout << "sum = (" << sum.real << ", " << sum.imag << ")\n"; |
50 | | - std::cout << "product = (" << product.real << ", " << product.imag << ")\n"; |
51 | | - } |
52 | | -} |
53 | | -``` |
| 9 | +@include ex3.cpp |
54 | 10 |
|
55 | 11 | Output (running with `-n 5`): |
56 | 12 |
|
|
0 commit comments