Logo AND Algorithmique Numérique Distribuée

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