Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
update comm status BEFORE sending signals
[simgrid.git] / examples / cpp / exec-waitany / s4u-exec-waitany.cpp
1 /* Copyright (c) 2019-2023. 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
11 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_exec_waitany, "Messages specific for this s4u example");
12 namespace sg4 = simgrid::s4u;
13
14 static void worker(bool with_timeout)
15 {
16   /* Vector in which we store all pending executions*/
17   std::vector<sg4::ExecPtr> pending_executions;
18
19   for (int i = 0; i < 3; i++) {
20     std::string name = "Exec-" + std::to_string(i);
21     double amount    = (6 * (i % 2) + i + 1) * sg4::this_actor::get_host()->get_speed();
22
23     sg4::ExecPtr exec = sg4::this_actor::exec_init(amount)->set_name(name);
24     pending_executions.push_back(exec);
25     exec->start();
26
27     XBT_INFO("Activity %s has started for %.0f seconds", name.c_str(),
28              amount / sg4::this_actor::get_host()->get_speed());
29   }
30
31   /* Now that executions were initiated, wait for their completion, in order of termination.
32    *
33    * This loop waits for first terminating execution with wait_any() and remove it with erase(), until all execs are
34    * terminated.
35    */
36   while (not pending_executions.empty()) {
37     ssize_t pos;
38     if (with_timeout)
39       pos = sg4::Exec::wait_any_for(pending_executions, 4);
40     else
41       pos = sg4::Exec::wait_any(pending_executions);
42
43     if (pos < 0) {
44       XBT_INFO("Do not wait any longer for an activity");
45       pending_executions.clear();
46     } else {
47       XBT_INFO("Activity '%s' (at position %zd) is complete", pending_executions[pos]->get_cname(), pos);
48       pending_executions.erase(pending_executions.begin() + pos);
49     }
50     XBT_INFO("%zu activities remain pending", pending_executions.size());
51   }
52 }
53
54 int main(int argc, char* argv[])
55 {
56   sg4::Engine e(&argc, argv);
57   e.load_platform(argv[1]);
58   sg4::Actor::create("worker", e.host_by_name("Tremblay"), worker, false);
59   sg4::Actor::create("worker_timeout", e.host_by_name("Tremblay"), worker, true);
60   e.run();
61
62   return 0;
63 }