Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
adding documentation
[simgrid.git] / examples / cpp / synchro-semaphore / s4u-synchro-semaphore.cpp
1 /* Copyright (c) 2006-2023. 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 // This example implements a simple producer/consumer schema,
7 // passing a bunch of items from one to the other
8
9 #include "simgrid/s4u.hpp"
10
11 #include <memory>
12
13 namespace sg4 = simgrid::s4u;
14
15 XBT_LOG_NEW_DEFAULT_CATEGORY(sem_test, "Simple test of the semaphore");
16
17 static void producer(std::string& buffer, sg4::SemaphorePtr sem_empty, sg4::SemaphorePtr sem_full,
18                      const std::vector<std::string>& args)
19 {
20   for (auto const& str : args) {
21     sem_empty->acquire();
22     XBT_INFO("Pushing '%s'", str.c_str());
23     buffer = str;
24     sem_full->release();
25   }
26
27   XBT_INFO("Bye!");
28 }
29 static void consumer(const std::string& buffer, sg4::SemaphorePtr sem_empty, sg4::SemaphorePtr sem_full)
30 {
31   std::string str;
32   do {
33     sem_full->acquire();
34     str = buffer;
35     XBT_INFO("Receiving '%s'", str.c_str());
36     sem_empty->release();
37   } while (str != "");
38
39   XBT_INFO("Bye!");
40 }
41
42 int main(int argc, char **argv)
43 {
44   std::vector<std::string> args({"one", "two", "three", ""});
45   sg4::Engine e(&argc, argv);
46   e.load_platform(argc > 1 ? argv[1] : "../../platforms/two_hosts.xml");
47
48   std::string buffer;                         /* Where the data is exchanged */
49   auto sem_empty = sg4::Semaphore::create(1); /* indicates whether the buffer is empty */
50   auto sem_full  = sg4::Semaphore::create(0); /* indicates whether the buffer is full */
51
52   sg4::Actor::create("producer", e.host_by_name("Tremblay"), producer, std::ref(buffer), sem_empty, sem_full,
53                      std::cref(args));
54   sg4::Actor::create("consumer", e.host_by_name("Jupiter"), consumer, std::cref(buffer), sem_empty, sem_full);
55   e.run();
56
57   return 0;
58 }