Logo AND Algorithmique Numérique Distribuée

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