Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add new entry in Release_Notes.
[simgrid.git] / examples / cpp / synchro-condition-variable / s4u-synchro-condition-variable.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 #include <mutex>           /* std::mutex and std::scoped_lock */
7 #include <simgrid/s4u.hpp> /* All of S4U */
8
9 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_test, "a sample log category");
10 namespace sg4 = simgrid::s4u;
11
12 static void worker_fun(sg4::ConditionVariablePtr cv, sg4::MutexPtr mutex, std::string& data, bool& done)
13 {
14   const std::scoped_lock lock(*mutex);
15
16   XBT_INFO("Start processing data which is '%s'.", data.c_str());
17   data += " after processing";
18
19   // Send data back to main()
20   XBT_INFO("Signal to master that the data processing is completed, and exit.");
21
22   done = true;
23   cv->notify_one();
24 }
25
26 static void master_fun()
27 {
28   auto mutex  = sg4::Mutex::create();
29   auto cv     = sg4::ConditionVariable::create();
30   std::string data = "Example data";
31   bool done        = false;
32
33   auto worker = sg4::Actor::create("worker", sg4::Host::by_name("Jupiter"), worker_fun, cv, mutex, std::ref(data),
34                                    std::ref(done));
35
36   // wait for the worker
37   cv->wait(std::unique_lock(*mutex), [&done]() { return done; });
38   XBT_INFO("data is now '%s'.", data.c_str());
39
40   worker->join();
41 }
42
43 int main(int argc, char** argv)
44 {
45   sg4::Engine e(&argc, argv);
46   e.load_platform("../../platforms/two_hosts.xml");
47   sg4::Actor::create("main", e.host_by_name("Tremblay"), master_fun);
48   e.run();
49
50   return 0;
51 }