Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
6f8a4ce11b10ec89648ee2e0c8866d60c7f100f1
[simgrid.git] / examples / cpp / app-token-ring / s4u-app-token-ring.cpp
1 /* Copyright (c) 2017-2022. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include <simgrid/s4u.hpp>
7 #include <algorithm>
8 #include <string>
9 #include <map>
10 #include <vector>
11
12 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_app_token_ring, "Messages specific for this s4u example");
13 namespace sg4 = simgrid::s4u;
14
15 class RelayRunner {
16 public:
17   explicit RelayRunner() = default;
18
19   void operator()() const
20   {
21     size_t token_size = 1000000; /* The token is 1MB long*/
22     sg4::Mailbox* my_mailbox;
23     sg4::Mailbox* neighbor_mailbox;
24     unsigned int rank = 0;
25
26     try {
27       rank = std::stoi(sg4::this_actor::get_name());
28     } catch (const std::invalid_argument& ia) {
29       throw std::invalid_argument(std::string("Actors of this example must have a numerical name, not ") + ia.what());
30     }
31     my_mailbox = sg4::Mailbox::by_name(std::to_string(rank));
32     if (rank + 1 == sg4::Engine::get_instance()->get_host_count())
33       /* The last actor sends the token back to rank 0 */
34       neighbor_mailbox = sg4::Mailbox::by_name("0");
35     else
36       /* The others actors send to their right neighbor (rank+1) */
37       neighbor_mailbox = sg4::Mailbox::by_name(std::to_string(rank + 1));
38
39     if (rank == 0) {
40       /* The root actor (rank 0) first sends the token then waits to receive it back */
41       XBT_INFO("Host \"%u\" send 'Token' to Host \"%s\"", rank, neighbor_mailbox->get_cname());
42       std::string msg = "Token";
43       neighbor_mailbox->put(&msg, token_size);
44       const auto* res = my_mailbox->get<std::string>();
45       XBT_INFO("Host \"%u\" received \"%s\"", rank, res->c_str());
46     } else {
47       auto* res = my_mailbox->get<std::string>();
48       XBT_INFO("Host \"%u\" received \"%s\"", rank, res->c_str());
49       XBT_INFO("Host \"%u\" send 'Token' to Host \"%s\"", rank, neighbor_mailbox->get_cname());
50       neighbor_mailbox->put(res, token_size);
51     }
52   }
53 };
54
55 int main(int argc, char** argv)
56 {
57   sg4::Engine e(&argc, argv);
58   xbt_assert(argc > 1, "Usage: %s platform.xml\n", argv[0]);
59   e.load_platform(argv[1]);
60
61   XBT_INFO("Number of hosts '%zu'", e.get_host_count());
62   int id = 0;
63   std::vector<sg4::Host*> list = e.get_all_hosts();
64   for (auto const& host : list) {
65     /* - Give a unique rank to each host and create a @ref relay_runner actor on each */
66     sg4::Actor::create((std::to_string(id)).c_str(), host, RelayRunner());
67     id++;
68   }
69   e.run();
70   XBT_INFO("Simulation time %g", sg4::Engine::get_clock());
71
72   return 0;
73 }