Ticket #2007: mpi-test.cpp

File mpi-test.cpp, 1.8 KB (added by manuel.freiberger@…, 14 years ago)

Example code

Line 
1#include <boost/mpi.hpp>
2#include <boost/serialization/export.hpp>
3
4#include <iostream>
5
6// the next two headers are critical for compilation/linking
7//#include <boost/archive/impl/archive_pointer_iserializer.ipp>
8//#include <boost/archive/impl/archive_pointer_oserializer.ipp>
9
10namespace mpi = boost::mpi;
11
12class Base
13{
14 public:
15 virtual int get() const { return 1; }
16
17 private:
18 friend class boost::serialization::access;
19
20 template <class TArchive>
21 void serialize(TArchive& archive, const unsigned int version) {}
22};
23
24class Derived : public Base
25{
26 public:
27 virtual int get() const { return 2; }
28
29 private:
30 // grant Boost.serialize access to this class
31 friend class boost::serialization::access;
32
33 template <class TArchive>
34 void serialize(TArchive& archive, const unsigned int version)
35 {
36 // serialize base class
37 archive & boost::serialization::base_object<Base>(*this);
38 }
39};
40
41BOOST_CLASS_EXPORT(Derived)
42
43int main(int argc, char* argv[])
44{
45 mpi::environment env(argc, argv);
46 mpi::communicator world;
47
48 if (world.rank() == 0)
49 {
50 // send a Derived
51 Base* b = new Derived;
52 std::cout << "Process " << world.rank() << " sends object with b->get() = " << b->get() << std::endl;
53 world.send(1, 0, b);
54 delete b;
55
56 // receive a Base
57 world.recv(1, 1, b);
58 std::cout << "Process " << world.rank() << " got object with b->get() = " << b->get() << std::endl;
59 delete b;
60 }
61 else
62 {
63 // receive a Derived
64 Base* b;
65 world.recv(0, 0, b);
66 std::cout << "Process " << world.rank() << " got object with b->get() = " << b->get() << std::endl;
67 delete b;
68
69 // send a Base
70 b = new Base;
71 std::cout << "Process " << world.rank() << " sends object with b->get() = " << b->get() << std::endl;
72 world.send(0, 1, b);
73 delete b;
74 }
75
76 return 0;
77}