Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines for 2022.
[simgrid.git] / examples / cpp / exec-async / s4u-exec-async.cpp
1 /* Copyright (c) 2007-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
8 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_test, "Messages specific for this s4u example");
9
10 /* This actor simply waits for its activity completion after starting it.
11  * That's exactly equivalent to synchronous execution. */
12 static void waiter()
13 {
14   double computation_amount = simgrid::s4u::this_actor::get_host()->get_speed();
15   XBT_INFO("Execute %g flops, should take 1 second.", computation_amount);
16   simgrid::s4u::ExecPtr activity = simgrid::s4u::this_actor::exec_init(computation_amount);
17   activity->start();
18   activity->wait();
19
20   XBT_INFO("Goodbye now!");
21 }
22
23 /* This actor tests the ongoing execution until its completion, and don't wait before it's terminated. */
24 static void monitor()
25 {
26   double computation_amount = simgrid::s4u::this_actor::get_host()->get_speed();
27   XBT_INFO("Execute %g flops, should take 1 second.", computation_amount);
28   simgrid::s4u::ExecPtr activity = simgrid::s4u::this_actor::exec_init(computation_amount);
29   activity->start();
30
31   while (not activity->test()) {
32     XBT_INFO("Remaining amount of flops: %g (%.0f%%)", activity->get_remaining(),
33              100 * activity->get_remaining_ratio());
34     simgrid::s4u::this_actor::sleep_for(0.3);
35   }
36
37   XBT_INFO("Goodbye now!");
38 }
39
40 /* This actor cancels the ongoing execution after a while. */
41 static void canceller()
42 {
43   double computation_amount = simgrid::s4u::this_actor::get_host()->get_speed();
44
45   XBT_INFO("Execute %g flops, should take 1 second.", computation_amount);
46   simgrid::s4u::ExecPtr activity = simgrid::s4u::this_actor::exec_async(computation_amount);
47   simgrid::s4u::this_actor::sleep_for(0.5);
48   XBT_INFO("I changed my mind, cancel!");
49   activity->cancel();
50
51   XBT_INFO("Goodbye now!");
52 }
53
54 int main(int argc, char* argv[])
55 {
56   simgrid::s4u::Engine e(&argc, argv);
57   e.load_platform(argv[1]);
58
59   simgrid::s4u::Host* fafard  = e.host_by_name("Fafard");
60   simgrid::s4u::Host* ginette = e.host_by_name("Ginette");
61   simgrid::s4u::Host* boivin  = e.host_by_name("Boivin");
62
63   simgrid::s4u::Actor::create("wait", fafard, waiter);
64   simgrid::s4u::Actor::create("monitor", ginette, monitor);
65   simgrid::s4u::Actor::create("cancel", boivin, canceller);
66
67   e.run();
68
69   XBT_INFO("Simulation time %g", simgrid::s4u::Engine::get_clock());
70
71   return 0;
72 }