Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines.
[simgrid.git] / examples / s4u / synchro-semaphore / s4u-synchro-semaphore.cpp
1 /* Copyright (c) 2006-2021. 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 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_test, "a sample log category");
14
15 const char* buffer;                                                        /* Where the data is exchanged */
16 simgrid::s4u::SemaphorePtr sem_empty = simgrid::s4u::Semaphore::create(1); /* indicates whether the buffer is empty */
17 simgrid::s4u::SemaphorePtr sem_full  = simgrid::s4u::Semaphore::create(0); /* indicates whether the buffer is full */
18
19 static void producer(const std::vector<std::string>* args)
20 {
21   for (auto const& str : *args) {
22     sem_empty->acquire();
23     XBT_INFO("Pushing '%s'", str.c_str());
24     buffer = str.c_str();
25     sem_full->release();
26   }
27
28   XBT_INFO("Bye!");
29 }
30 static void consumer()
31 {
32   std::string str;
33   do {
34     sem_full->acquire();
35     str = buffer;
36     XBT_INFO("Receiving '%s'", str.c_str());
37     sem_empty->release();
38   } while (str != "");
39
40   XBT_INFO("Bye!");
41 }
42
43 int main(int argc, char **argv)
44 {
45   std::vector<std::string> args({"one", "two", "three", ""});
46   simgrid::s4u::Engine e(&argc, argv);
47   e.load_platform("../../platforms/two_hosts.xml");
48   simgrid::s4u::Actor::create("producer", simgrid::s4u::Host::by_name("Tremblay"), producer, &args);
49   simgrid::s4u::Actor::create("consumer", simgrid::s4u::Host::by_name("Jupiter"), consumer);
50   e.run();
51
52   return 0;
53 }