Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add missing license
[simgrid.git] / examples / python / comm-waitall / comm-waitall.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 """
7 This example shows how to block on the completion of a set of communications.
8
9 As for the other asynchronous examples, the sender initiate all the messages it wants to send and
10 pack the resulting simgrid.Comm objects in a list. All messages thus occur concurrently.
11
12 The sender then blocks until all ongoing communication terminate, using simgrid.Comm.wait_all()
13 """
14
15 import sys
16 from simgrid import Actor, Comm, Engine, Host, Mailbox, this_actor
17
18
19 def sender(messages_count, msg_size, receivers_count):
20     # List in which we store all ongoing communications
21     pending_comms = []
22
23     # Vector of the used mailboxes
24     mboxes = [Mailbox.by_name("receiver-{:d}".format(i))
25               for i in range(0, receivers_count)]
26
27     # Start dispatching all messages to receivers, in a round robin fashion
28     for i in range(0, messages_count):
29         content = "Message {:d}".format(i)
30         mbox = mboxes[i % receivers_count]
31
32         this_actor.info("Send '{:s}' to '{:s}'".format(content, str(mbox)))
33
34         # Create a communication representing the ongoing communication, and store it in pending_comms
35         comm = mbox.put_async(content, msg_size)
36         pending_comms.append(comm)
37
38     # Start sending messages to let the workers know that they should stop
39     for i in range(0, receivers_count):
40         mbox = mboxes[i]
41         this_actor.info("Send 'finalize' to '{:s}'".format(str(mbox)))
42         comm = mbox.put_async("finalize", 0)
43         pending_comms.append(comm)
44
45     this_actor.info("Done dispatching all messages")
46
47     # Now that all message exchanges were initiated, wait for their completion in one single call
48     Comm.wait_all(pending_comms)
49
50     this_actor.info("Goodbye now!")
51
52
53 def receiver(my_id):
54     mbox = Mailbox.by_name("receiver-{:d}".format(my_id))
55
56     this_actor.info("Wait for my first message")
57     while True:
58         received = mbox.get()
59         this_actor.info("I got a '{:s}'.".format(received))
60         if received == "finalize":
61             break  # If it's a finalize message, we're done.
62
63
64 if __name__ == '__main__':
65     e = Engine(sys.argv)
66
67     # Load the platform description
68     e.load_platform(sys.argv[1])
69
70     Actor.create("sender", Host.by_name("Tremblay"), sender, 5, 1000000, 2)
71     Actor.create("receiver", Host.by_name("Ruby"), receiver, 0)
72     Actor.create("receiver", Host.by_name("Perl"), receiver, 1)
73
74     e.run()