Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines for 2023.
[simgrid.git] / examples / cpp / comm-suspend / s4u-comm-suspend.cpp
1 /* Copyright (c) 2010-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 shows how to suspend and resume an asynchronous communication. */
7
8 #include "simgrid/s4u.hpp"
9 #include <cstdlib>
10 #include <iostream>
11 #include <string>
12 namespace sg4 = simgrid::s4u;
13
14 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_comm_wait, "Messages specific for this s4u example");
15
16 static void sender()
17 {
18   sg4::Mailbox* mbox = sg4::Mailbox::by_name("receiver");
19
20   // Copy the data we send: the 'msg_content' variable is not a stable storage location.
21   // It will be destroyed when this actor leaves the loop, ie before the receiver gets the data
22   auto* payload = new std::string("Sent message");
23
24   /* Create a communication representing the ongoing communication and then */
25   sg4::CommPtr comm = mbox->put_init(payload, 13194230);
26   XBT_INFO("Suspend the communication before it starts (remaining: %.0f bytes) and wait a second.",
27            comm->get_remaining());
28   sg4::this_actor::sleep_for(1);
29   XBT_INFO("Now, start the communication (remaining: %.0f bytes) and wait another second.", comm->get_remaining());
30   comm->start();
31   sg4::this_actor::sleep_for(1);
32
33   XBT_INFO("There is still %.0f bytes to transfer in this communication. Suspend it for one second.",
34            comm->get_remaining());
35   comm->suspend();
36   XBT_INFO("Now there is %.0f bytes to transfer. Resume it and wait for its completion.", comm->get_remaining());
37   comm->resume();
38   comm->wait();
39   XBT_INFO("There is %f bytes to transfer after the communication completion.", comm->get_remaining());
40   XBT_INFO("Suspending a completed activity is a no-op.");
41   comm->suspend();
42 }
43
44 static void receiver()
45 {
46   sg4::Mailbox* mbox = sg4::Mailbox::by_name("receiver");
47   XBT_INFO("Wait for the message.");
48   auto received = mbox->get_unique<std::string>();
49
50   XBT_INFO("I got '%s'.", received->c_str());
51 }
52
53 int main(int argc, char* argv[])
54 {
55   sg4::Engine e(&argc, argv);
56
57   e.load_platform(argv[1]);
58
59   sg4::Actor::create("sender", e.host_by_name("Tremblay"), sender);
60   sg4::Actor::create("receiver", e.host_by_name("Jupiter"), receiver);
61
62   e.run();
63
64   return 0;
65 }