Logo AND Algorithmique Numérique Distribuée

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