Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
rename create to init. add init with name only. add setters
[simgrid.git] / examples / cpp / operation-switch-host / s4u-operation-switch-host.cpp
1 /* Copyright (c) 2017-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 /* This example demonstrates how to dynamically modify a graph of operations.
7  *
8  * Assuming we have two instances of a service placed on different hosts,
9  * we want to send data alternatively to thoses instances.
10  *
11  * We consider the following graph:
12  *
13  * comm0 -> exec1 -> comm1
14  *     ↳-> exec2 ->comm2
15  *
16  * With exec1 and exec2 on different hosts.
17  */
18
19 #include "simgrid/plugins/operation.hpp"
20 #include "simgrid/s4u.hpp"
21
22 XBT_LOG_NEW_DEFAULT_CATEGORY(operation_switch_host, "Messages specific for this operation example");
23
24 int main(int argc, char* argv[])
25 {
26   simgrid::s4u::Engine e(&argc, argv);
27   e.load_platform(argv[1]);
28   simgrid::plugins::Operation::init();
29
30   // Retrieve hosts
31   auto tremblay = e.host_by_name("Tremblay");
32   auto jupiter  = e.host_by_name("Jupiter");
33   auto fafard   = e.host_by_name("Fafard");
34
35   // Create operations
36   auto comm0 = simgrid::plugins::CommOp::init("comm0");
37   comm0->set_bytes(1e7);
38   comm0->set_source(tremblay);
39   auto exec1 = simgrid::plugins::ExecOp::init("exec1", 1e9, jupiter);
40   auto exec2 = simgrid::plugins::ExecOp::init("exec2", 1e9, fafard);
41   auto comm1 = simgrid::plugins::CommOp::init("comm1", 1e7, jupiter, tremblay);
42   auto comm2 = simgrid::plugins::CommOp::init("comm2", 1e7, fafard, tremblay);
43
44   // Create the initial graph by defining dependencies between operations
45   comm0->add_successor(exec2);
46   exec1->add_successor(comm1);
47   exec2->add_successor(comm2);
48
49   // Add a function to be called when operations end for log purpose
50   simgrid::plugins::Operation::on_end_cb([](simgrid::plugins::Operation* op) {
51     XBT_INFO("Operation %s finished (%d)", op->get_name().c_str(), op->get_count());
52   });
53
54   // Add a function to be called before each executions of comm0
55   // This function modifies the graph of operations by adding or removing
56   // successors to comm0
57   int count = 0;
58   comm0->on_this_start([&](simgrid::plugins::Operation* op) {
59     if (count % 2 == 0) {
60       comm0->set_destination(jupiter);
61       comm0->add_successor(exec1);
62       comm0->remove_successor(exec2);
63     } else {
64       comm0->set_destination(fafard);
65       comm0->add_successor(exec2);
66       comm0->remove_successor(exec1);
67     }
68     count++;
69   });
70
71   // Enqueue four executions for operation comm0
72   comm0->enqueue_execs(4);
73
74   // Start the simulation
75   e.run();
76   return 0;
77 }