Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
6044c2d89983c5e85be8bca0cccbe8dbf26cde45
[simgrid.git] / examples / s4u / synchro-semaphore / s4u-synchro-semaphore.cpp
1 /* Copyright (c) 2006-2019. 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
20 static void producer(std::vector<std::string>* args)
21 {
22   for (auto str : *args) {
23     sem_empty->acquire();
24     XBT_INFO("Pushing '%s'", str.c_str());
25     buffer = str.c_str();
26     sem_full->release();
27   }
28
29   XBT_INFO("Bye!");
30 }
31 static void consumer()
32 {
33   std::string str;
34   do {
35     sem_full->acquire();
36     str = buffer;
37     XBT_INFO("Receiving '%s'", str.c_str());
38     sem_empty->release();
39   } while (str != "");
40
41   XBT_INFO("Bye!");
42 }
43
44 int main(int argc, char **argv)
45 {
46   std::vector<std::string> args = std::vector<std::string>({"one", "two", "three", ""});
47   simgrid::s4u::Engine e(&argc, argv);
48   e.load_platform("../../platforms/two_hosts.xml");
49   simgrid::s4u::Actor::create("producer", simgrid::s4u::Host::by_name("Tremblay"), producer, &args);
50   simgrid::s4u::Actor::create("consumer", simgrid::s4u::Host::by_name("Jupiter"), consumer);
51   e.run();
52
53   return 0;
54 }