1 /* Copyright (c) 2017-2023. The SimGrid Team. All rights reserved. */
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. */
6 /* This example demonstrates how to dynamically modify a graph of tasks.
8 * Assuming we have two instances of a service placed on different hosts,
9 * we want to send data alternatively to thoses instances.
11 * We consider the following graph:
13 * comm0 -> exec1 -> comm1
16 * With exec1 and exec2 on different hosts.
19 #include "simgrid/s4u.hpp"
21 XBT_LOG_NEW_DEFAULT_CATEGORY(task_switch_host, "Messages specific for this task example");
22 namespace sg4 = simgrid::s4u;
24 int main(int argc, char* argv[])
26 sg4::Engine e(&argc, argv);
27 e.load_platform(argv[1]);
30 auto* tremblay = e.host_by_name("Tremblay");
31 auto* jupiter = e.host_by_name("Jupiter");
32 auto* fafard = e.host_by_name("Fafard");
35 auto comm0 = sg4::CommTask::init("comm0");
36 comm0->set_bytes(1e7);
37 comm0->set_source(tremblay);
38 auto exec1 = sg4::ExecTask::init("exec1", 1e9, jupiter);
39 auto exec2 = sg4::ExecTask::init("exec2", 1e9, fafard);
40 auto comm1 = sg4::CommTask::init("comm1", 1e7, jupiter, tremblay);
41 auto comm2 = sg4::CommTask::init("comm2", 1e7, fafard, tremblay);
43 // Create the initial graph by defining dependencies between tasks
44 comm0->add_successor(exec2);
45 exec1->add_successor(comm1);
46 exec2->add_successor(comm2);
48 // Add a function to be called when tasks end for log purpose
49 sg4::Task::on_completion_cb(
50 [](const sg4::Task* t) { XBT_INFO("Task %s finished (%d)", t->get_name().c_str(), t->get_count()); });
52 // Add a function to be called before each firing of comm0
53 // This function modifies the graph of tasks by adding or removing
54 // successors to comm0
55 comm0->on_this_start_cb([&comm0, exec1, exec2, jupiter, fafard](const sg4::Task*) {
58 comm0->set_destination(jupiter);
60 comm0->set_destination(fafard);
64 comm0->on_this_completion_cb([&comm0, exec1, exec2](const sg4::Task*) {
67 comm0->add_successor(exec1);
68 comm0->remove_successor(exec2);
70 comm0->add_successor(exec2);
71 comm0->remove_successor(exec1);
76 // Enqueue four firings for task comm0
77 comm0->enqueue_firings(4);
79 // Start the simulation