1 /* Copyright (c) 2010-2021. 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 /* ************************************************************************* */
7 /* Take this tutorial online: https://simgrid.frama.io/simgrid/tuto_s4u.html */
8 /* ************************************************************************* */
10 #include <simgrid/s4u.hpp>
12 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_app_masterworker, "Messages specific for this example");
15 static void master(std::vector<std::string> args)
17 xbt_assert(args.size() > 4, "The master function expects at least 3 arguments");
19 long tasks_count = std::stol(args[1]);
20 double compute_cost = std::stod(args[2]);
21 long communication_cost = std::stol(args[3]);
22 std::vector<simgrid::s4u::Mailbox*> workers;
23 for (unsigned int i = 4; i < args.size(); i++)
24 workers.push_back(simgrid::s4u::Mailbox::by_name(args[i]));
26 XBT_INFO("Got %zu workers and %ld tasks to process", workers.size(), tasks_count);
28 for (int i = 0; i < tasks_count; i++) { /* For each task to be executed: */
29 /* - Select a worker in a round-robin way */
30 simgrid::s4u::Mailbox* mailbox = workers[i % workers.size()];
32 /* - Send the computation cost to that worker */
33 XBT_INFO("Sending task %d of %ld to mailbox '%s'", i, tasks_count, mailbox->get_cname());
34 mailbox->put(new double(compute_cost), communication_cost);
37 XBT_INFO("All tasks have been dispatched. Request all workers to stop.");
38 for (unsigned int i = 0; i < workers.size(); i++) {
39 /* The workers stop when receiving a negative compute_cost */
40 simgrid::s4u::Mailbox* mailbox = workers[i % workers.size()];
42 mailbox->put(new double(-1.0), 0);
48 static void worker(std::vector<std::string> args)
50 xbt_assert(args.size() == 1, "The worker expects no argument");
52 const simgrid::s4u::Host* my_host = simgrid::s4u::this_actor::get_host();
53 simgrid::s4u::Mailbox* mailbox = simgrid::s4u::Mailbox::by_name(my_host->get_name());
57 auto msg = mailbox->get_unique<double>();
60 if (compute_cost > 0) /* If compute_cost is valid, execute a computation of that cost */
61 simgrid::s4u::this_actor::execute(compute_cost);
62 } while (compute_cost > 0); /* Stop when receiving an invalid compute_cost */
64 XBT_INFO("Exiting now.");
69 int main(int argc, char* argv[])
71 simgrid::s4u::Engine e(&argc, argv);
72 xbt_assert(argc > 2, "Usage: %s platform_file deployment_file\n", argv[0]);
74 /* Register the functions representing the actors */
75 e.register_function("master", &master);
76 e.register_function("worker", &worker);
78 /* Load the platform description and then deploy the application */
79 e.load_platform(argv[1]);
80 e.load_deployment(argv[2]);
82 /* Run the simulation */
85 XBT_INFO("Simulation is over");