Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
fe84e47e803830d26f9c0a0d5c3000d796642c5a
[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     # When using a context manager, the lock and the unlock are automatic. This is the easiest approach
37     with mutex:
38         this_actor.info(f"Hello simgrid, I'm ready to compute after acquiring the mutex from a context manager")
39         result.value += 1
40     this_actor.info(f"I'm done, good bye")
41
42
43 def worker(mutex: Mutex, result: ResultHolder):
44     # If you lock your mutex manually, you also have to unlock it.
45     # Beware of exceptions preventing your unlock() from being executed!
46     mutex.lock()
47     this_actor.info("Hello simgrid, I'm ready to compute after a regular lock")
48     result.value += 1
49     mutex.unlock()
50     this_actor.info("I'm done, good bye")
51
52
53
54 def main():
55     settings = create_parser().parse_known_args()[0]
56     e = Engine(sys.argv)
57     e.load_platform(settings.platform)
58
59     # Create the requested amount of actors pairs. Each pair has a specific mutex and cell in `result`
60     results = [ResultHolder(value=0) for _ in range(settings.actors)]
61     for i in range(settings.actors):
62         mutex = Mutex()
63         Actor.create(f"worker-{i}(mgr)", Host.by_name("Jupiter"), worker_context_manager, mutex, results[i])
64         Actor.create(f"worker-{i}", Host.by_name("Tremblay"), worker, mutex, results[i])
65
66     e.run()
67
68     for i in range(settings.actors):
69         this_actor.info(f"Result[{i}] -> {results[i].value}")
70
71
72 if __name__ == "__main__":
73     main()