Logo AND Algorithmique Numérique Distribuée

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