Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Plug a memleak
[simgrid.git] / examples / cpp / io-async / s4u-io-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 static void test(sg_size_t size)
12 {
13   const sg4::Disk* disk = sg4::Host::current()->get_disks().front();
14   XBT_INFO("Hello! read %llu bytes from %s", size, disk->get_cname());
15
16   sg4::IoPtr activity = disk->io_init(size, sg4::Io::OpType::READ);
17   activity->start();
18   activity->wait();
19
20   XBT_INFO("Goodbye now!");
21 }
22
23 static void test_waitfor(sg_size_t size)
24 {
25   const sg4::Disk* disk = sg4::Host::current()->get_disks().front();
26   XBT_INFO("Hello! write %llu bytes from %s", size, disk->get_cname());
27
28   sg4::IoPtr activity = disk->write_async(size);
29   try {
30     activity->wait_for(0.5);
31   } catch (const simgrid::TimeoutException&) {
32     XBT_INFO("Asynchronous write: Timeout!");
33   }
34
35   XBT_INFO("Goodbye now!");
36 }
37
38 static void test_cancel(sg_size_t size)
39 {
40   const sg4::Disk* disk = sg4::Host::current()->get_disks().front();
41   sg4::this_actor::sleep_for(0.5);
42   XBT_INFO("Hello! write %llu bytes from %s", size, disk->get_cname());
43
44   sg4::IoPtr activity = disk->write_async(size);
45   sg4::this_actor::sleep_for(0.5);
46   XBT_INFO("I changed my mind, cancel!");
47   activity->cancel();
48
49   XBT_INFO("Goodbye now!");
50 }
51
52 static void test_monitor(sg_size_t size)
53 {
54   const sg4::Disk* disk = sg4::Host::current()->get_disks().front();
55   sg4::this_actor::sleep_for(1);
56   sg4::IoPtr activity = disk->write_async(size);
57
58   while (not activity->test()) {
59     XBT_INFO("Remaining amount of bytes to write: %g", activity->get_remaining());
60     sg4::this_actor::sleep_for(0.2);
61   }
62   activity->wait();
63
64   XBT_INFO("Goodbye now!");
65 }
66
67 int main(int argc, char* argv[])
68 {
69   sg4::Engine e(&argc, argv);
70   e.load_platform(argv[1]);
71   sg4::Actor::create("test", e.host_by_name("bob"), test, 2e7);
72   sg4::Actor::create("test_waitfor", e.host_by_name("alice"), test_waitfor, 5e7);
73   sg4::Actor::create("test_cancel", e.host_by_name("alice"), test_cancel, 5e7);
74   sg4::Actor::create("test_monitor", e.host_by_name("alice"), test_monitor, 5e7);
75
76   e.run();
77
78   XBT_INFO("Simulation time %g", sg4::Engine::get_clock());
79
80   return 0;
81 }