Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Remove explicit conversion to std::string when it's not required.
[simgrid.git] / examples / cpp / comm-testany / s4u-comm-testany.cpp
1 /* Copyright (c) 2010-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 <cstdlib>
8 #include <iostream>
9 #include <string>
10 namespace sg4 = simgrid::s4u;
11
12 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_comm_testany, "Messages specific for this s4u example");
13
14 static void rank0()
15 {
16   sg4::Mailbox* mbox = sg4::Mailbox::by_name("rank0");
17   std::string* msg1;
18   std::string* msg2;
19   std::string* msg3;
20
21   XBT_INFO("Post my asynchronous receives");
22   auto comm1                              = mbox->get_async(&msg1);
23   auto comm2                              = mbox->get_async(&msg2);
24   auto comm3                              = mbox->get_async(&msg3);
25   std::vector<sg4::CommPtr> pending_comms = {comm1, comm2, comm3};
26
27   XBT_INFO("Send some data to rank-1");
28   for (int i = 0; i < 3; i++)
29     sg4::Mailbox::by_name("rank1")->put(new int(i), 1);
30
31   XBT_INFO("Test for completed comms");
32   while (not pending_comms.empty()) {
33     ssize_t flag = sg4::Comm::test_any(pending_comms);
34     if (flag != -1) {
35       pending_comms.erase(pending_comms.begin() + flag);
36       XBT_INFO("Remove a pending comm.");
37     } else // nothing matches, wait for a little bit
38       sg4::this_actor::sleep_for(0.1);
39   }
40   XBT_INFO("Last comm is complete");
41   delete msg1;
42   delete msg2;
43   delete msg3;
44 }
45
46 static void rank1()
47 {
48   sg4::Mailbox* rank0_mbox = sg4::Mailbox::by_name("rank0");
49   sg4::Mailbox* rank1_mbox = sg4::Mailbox::by_name("rank1");
50
51   for (int i = 0; i < 3; i++) {
52     auto res = rank1_mbox->get_unique<int>();
53     XBT_INFO("Received %d", *res);
54     std::string msg_content = "Message " + std::to_string(i);
55     auto* payload           = new std::string(msg_content);
56     XBT_INFO("Send '%s'", msg_content.c_str());
57     rank0_mbox->put(payload, 1e6);
58   }
59 }
60
61 int main(int argc, char* argv[])
62 {
63   sg4::Engine e(&argc, argv);
64
65   e.load_platform(argv[1]);
66
67   sg4::Actor::create("rank-0", e.host_by_name("Tremblay"), rank0);
68   sg4::Actor::create("rank-1", e.host_by_name("Fafard"), rank1);
69
70   e.run();
71
72   return 0;
73 }