Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines for 2023.
[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::lock_guard */
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 std::string data;
13 bool done = false;
14
15 static void worker_fun(sg4::ConditionVariablePtr cv, sg4::MutexPtr mutex)
16 {
17   std::unique_lock lock(*mutex);
18
19   XBT_INFO("Start processing data which is '%s'.", data.c_str());
20   data += " after processing";
21
22   // Send data back to main()
23   XBT_INFO("Signal to master that the data processing is completed, and exit.");
24
25   done = true;
26   cv->notify_one();
27 }
28
29 static void master_fun()
30 {
31   auto mutex  = sg4::Mutex::create();
32   auto cv     = sg4::ConditionVariable::create();
33   data        = "Example data";
34   auto worker = sg4::Actor::create("worker", sg4::Host::by_name("Jupiter"), worker_fun, cv, mutex);
35
36   // wait for the worker
37   cv->wait(std::unique_lock<sg4::Mutex>(*mutex), []() { 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 }