Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
ab46961ee4425162caaa653dd91721715d71d694
[simgrid.git] / examples / python / synchro-mutex / synchro-mutex.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 from argparse import ArgumentParser
7 from dataclasses import dataclass
8 import sys
9
10 from simgrid import Actor, Engine, Host, Mutex, this_actor
11
12
13 def create_parser() -> ArgumentParser:
14     parser = ArgumentParser()
15     parser.add_argument(
16         '--platform',
17         type=str,
18         required=True,
19         help='path to the platform description'
20     )
21     parser.add_argument(
22         '--actors',
23         type=int,
24         default=6,
25         help='how many pairs of actors should be started'
26     )
27     return parser
28
29
30 @dataclass
31 class ResultHolder:
32     value: int
33
34
35 def worker_context_manager(mutex: Mutex, result: ResultHolder):
36     with mutex:
37         this_actor.info(f"Hello simgrid, I'm ready to compute after acquiring the mutex from a context manager")
38         result.value += 1
39     this_actor.info(f"I'm done, good bye")
40
41
42 def worker(mutex: Mutex, result: ResultHolder):
43     mutex.lock()
44     this_actor.info("Hello simgrid, I'm ready to compute after a regular lock")
45     result.value += 1
46     mutex.unlock()
47     this_actor.info("I'm done, good bye")
48
49
50 def master(settings):
51     results = [ResultHolder(value=0) for _ in range(settings.actors)]
52     for i in range(settings.actors):
53         mutex = Mutex()
54         Actor.create(f"worker-{i}(mgr)", Host.by_name("Jupiter"), worker_context_manager, mutex, results[i])
55         Actor.create(f"worker-{i}", Host.by_name("Tremblay"), worker, mutex, results[i])
56     this_actor.sleep_for(10)
57     for i in range(settings.actors):
58         this_actor.info(f"Result[{i}] -> {results[i].value}")
59     this_actor.info("I'm done, good bye")
60
61
62 def main():
63     settings = create_parser().parse_known_args()[0]
64     e = Engine(sys.argv)
65     e.load_platform(settings.platform)
66     Actor.create("master", Host.by_name("Tremblay"), master, settings)
67     e.run()
68
69
70 if __name__ == "__main__":
71     main()