Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
58e5b162ea39b34c3782ccdbed1db0d63feeeb62
[simgrid.git] / examples / python / synchro-semaphore / synchro-semaphore.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 typing import List, Optional
7 from dataclasses import dataclass
8 from argparse import ArgumentParser
9 import sys
10
11 from simgrid import Actor, Engine, Host, Semaphore, this_actor
12
13
14 @dataclass
15 class Shared:
16     buffer: str
17
18
19 END_MARKER = ""
20
21
22 shared = Shared("")
23 sem_empty = Semaphore(1)  # indicates whether the buffer is empty
24 sem_full = Semaphore(0)  # indicates whether the buffer is full
25
26
27 def create_parser():
28     parser = ArgumentParser()
29     parser.add_argument(
30         '--platform',
31         type=str,
32         required=True,
33         help='path to the platform description'
34     )
35     parser.add_argument(
36         '--words',
37         type=lambda raw_words: raw_words.split(","),
38         default=["one", "two", "three"],
39         help='Comma-delimited list of words sent by the producer to the consumer'
40     )
41     return parser
42
43
44 def producer(words: List[str]):
45     this_actor.info("starting consuming")
46     for word in words + [END_MARKER]:
47         sem_empty.acquire()
48         this_actor.sleep_for(1)
49         this_actor.info(f"Pushing '{word}'")
50         shared.buffer = word
51         sem_full.release()
52     this_actor.info("Bye!")
53
54
55 def consumer():
56     this_actor.info("starting producing")
57     word: Optional[str] = None
58     while word != END_MARKER:
59         sem_full.acquire()
60         word = str(shared.buffer)
61         sem_empty.release()
62         this_actor.info(f"Receiving '{word}'")
63     this_actor.info("Bye!")
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     Actor.create("producer", Host.by_name("Tremblay"), producer, settings.words)
71     Actor.create("consumer", Host.by_name("Jupiter"), consumer)
72     e.run()
73
74
75 if __name__ == "__main__":
76     main()