Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
1d828cf367c7dd0a23e0d9b14ba595d5d82c9763
[simgrid.git] / examples / s4u / synchro-condition-variable / s4u-synchro-condition-variable.cpp
1 /* Copyright (c) 2006-2020. 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     std::unique_lock<simgrid::s4u::Mutex> lock(*mutex);
37     cv->wait(lock, []() { return done; });
38   }
39   XBT_INFO("data is now '%s'.", data.c_str());
40
41   worker->join();
42 }
43
44 int main(int argc, char** argv)
45 {
46   simgrid::s4u::Engine e(&argc, argv);
47   e.load_platform("../../platforms/two_hosts.xml");
48   simgrid::s4u::Actor::create("main", simgrid::s4u::Host::by_name("Tremblay"), master_fun);
49   e.run();
50
51   return 0;
52 }