Logo AND Algorithmique Numérique Distribuée

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