Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines for 2023.
[simgrid.git] / examples / python / exec-async / exec-async.py
1 # Copyright (c) 2018-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 """
7 Usage: exec-async.py platform_file [other parameters]
8 """
9
10 import sys
11 from simgrid import Actor, Engine, Host, this_actor
12
13
14 class Waiter:
15     """
16     This actor simply waits for its task completion after starting it.
17     That's exactly equivalent to synchronous execution.
18     """
19
20     def __call__(self):
21         computation_amount = this_actor.get_host().speed
22         this_actor.info("Waiter executes {:.0f} flops, should take 1 second.".format(computation_amount))
23         activity = this_actor.exec_init(computation_amount)
24         activity.start()
25         activity.wait()
26
27         this_actor.info("Goodbye from waiter!")
28
29
30 class Monitor:
31     """This actor tests the ongoing execution until its completion, and don't wait before it's terminated."""
32
33     def __call__(self):
34         computation_amount = this_actor.get_host().speed
35         this_actor.info("Monitor executes {:.0f} flops, should take 1 second.".format(computation_amount))
36         activity = this_actor.exec_init(computation_amount).start()
37
38         while not activity.test():
39             this_actor.info("Remaining amount of flops: {:.0f} ({:.0f}%)".format(
40                 activity.remaining, 100 * activity.remaining_ratio))
41             this_actor.sleep_for(0.3)
42         activity.wait()
43
44         this_actor.info("Goodbye from monitor!")
45
46
47 class Canceller:
48     """This actor cancels the ongoing execution after a while."""
49
50     def __call__(self):
51         computation_amount = this_actor.get_host().speed
52         this_actor.info("Canceller executes {:.0f} flops, should take 1 second.".format(computation_amount))
53         activity = this_actor.exec_async(computation_amount)
54
55         this_actor.sleep_for(0.5)
56         this_actor.info("I changed my mind, cancel!")
57         activity.cancel()
58
59         this_actor.info("Goodbye from canceller!")
60
61
62 if __name__ == '__main__':
63     e = Engine(sys.argv)
64     if len(sys.argv) < 2:
65         raise AssertionError("Usage: exec-async.py platform_file [other parameters]")
66
67     e.load_platform(sys.argv[1])
68
69     Actor.create("wait", Host.by_name("Fafard"), Waiter())
70     Actor.create("monitor", Host.by_name("Ginette"), Monitor())
71     Actor.create("cancel", Host.by_name("Boivin"), Canceller())
72
73     e.run()