Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
98b71d3210a80d527f516f7f1c5847bd6e36e7ab
[simgrid.git] / docs / source / tuto_s4u / master-workers-lab1.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 # Take this tutorial online: https://simgrid.org/doc/latest/Tutorial_Algorithms.html
8 # ##################################################################################
9
10 from simgrid import Actor, Engine, Host, Mailbox, this_actor
11 import sys
12
13 # master-begin
14 def master(*args):
15   if len(args) == 2:
16     raise AssertionError(
17             f"Actor master requires 4 parameters, but only {len(args)}")
18   worker_count = int(args[0])           
19   tasks_count = int(args[1])
20   compute_cost = int(args[2])
21   communicate_cost = int(args[3])
22   this_actor.info(f"Got {worker_count} workers and {tasks_count} tasks to process")
23
24   for i in range(tasks_count): # For each task to be executed: 
25       # - Select a worker in a round-robin way
26       mailbox = Mailbox.by_name(str(i % worker_count))
27
28       # - Send the computation amount to the worker
29       if (tasks_count < 10000 or (tasks_count < 100000 and i % 10000 == 0) or i % 100000 == 0):
30         this_actor.info(f"Sending task {i} of {tasks_count} to mailbox '{mailbox.name}'")
31       mailbox.put(compute_cost, communicate_cost)
32
33   this_actor.info("All tasks have been dispatched. Request all workers to stop.")
34   for i in range (worker_count):
35       # The workers stop when receiving a negative compute_cost
36       mailbox = Mailbox.by_name(str(i))
37       mailbox.put(-1, 0)
38 # master-end
39
40 # worker-begin
41 def worker(*args):
42   assert len(args) == 1, "The worker expects one argument"
43
44   mailbox = Mailbox.by_name(args[0])
45   done = False
46   while not done:
47     compute_cost = mailbox.get()
48     if compute_cost > 0: # If compute_cost is valid, execute a computation of that cost 
49       this_actor.execute(compute_cost)
50     else: # Stop when receiving an invalid compute_cost
51       done = True
52
53   this_actor.info("Exiting now.")
54 # worker-end
55
56 # main-begin
57 if __name__ == '__main__':
58     assert len(sys.argv) > 2, f"Usage: python app-masterworkers.py platform_file deployment_file"
59
60     e = Engine(sys.argv)
61
62     # Register the classes representing the actors
63     e.register_actor("master", master)
64     e.register_actor("worker", worker)
65
66     # Load the platform description and then deploy the application
67     e.load_platform(sys.argv[1]) 
68     e.load_deployment(sys.argv[2])
69
70     # Run the simulation
71     e.run()
72
73     this_actor.info("Simulation is over")
74 # main-end