Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
0209dc86a16d049ea4ce81e959c82c54f791f70f
[simgrid.git] / examples / python / comm-waituntil / comm-waituntil.py
1 # Copyright (c) 2010-2022. 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
9 from argparse import ArgumentParser
10 from typing import List
11 import sys
12
13 from simgrid import Actor, Comm, Engine, Mailbox, this_actor
14
15
16 FINALIZE_MESSAGE = "finalize"
17
18
19 def create_parser() -> ArgumentParser:
20     parser = ArgumentParser()
21     parser.add_argument(
22         '--platform',
23         type=str,
24         required=True,
25         help='path to the platform description'
26     )
27     return parser
28
29
30 def sender(receiver_mailbox: Mailbox, messages_count: int, payload_size: int):
31     pending_comms: List[Comm] = []
32     # Start dispatching all messages to the receiver
33     for i in range(messages_count):
34         payload = f"Message {i}"
35         this_actor.info(f"Send '{payload}' to '{receiver_mailbox.name}'")
36         # Create a communication representing the ongoing communication
37         comm = receiver_mailbox.put_async(payload, payload_size)
38         # Add this comm to the vector of all known comms
39         pending_comms.append(comm)
40
41     # Start the finalize signal to the receiver
42     final_comm = receiver_mailbox.put_async(FINALIZE_MESSAGE, 0)
43     pending_comms.append(final_comm)
44     this_actor.info(f"Send '{FINALIZE_MESSAGE}' to '{receiver_mailbox.name}'")
45     this_actor.info("Done dispatching all messages")
46
47     # Now that all message exchanges were initiated, wait for their completion, in order of creation
48     while pending_comms:
49         comm = pending_comms[-1]
50         comm.wait_until(Engine.clock + 1)
51         pending_comms.pop()  # remove it from the list
52     this_actor.info("Goodbye now!")
53
54
55 def receiver(mailbox: Mailbox):
56     this_actor.info("Wait for my first message")
57     finalized = False
58     while not finalized:
59         received: str = mailbox.get()
60         this_actor.info(f"I got a '{received}'.")
61         # If it's a finalize message, we're done.
62         if received == FINALIZE_MESSAGE:
63             finalized = True
64
65
66 def main():
67     settings = create_parser().parse_known_args()[0]
68     e = Engine(sys.argv)
69     e.load_platform(settings.platform)
70     receiver_mailbox: Mailbox = Mailbox.by_name("receiver")
71     Actor.create("sender", e.host_by_name("Tremblay"), sender, receiver_mailbox, 3, int(5e7))
72     Actor.create("receiver", e.host_by_name("Ruby"), receiver, receiver_mailbox)
73     e.run()
74
75
76 if __name__ == "__main__":
77     main()