Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of https://framagit.org/simgrid/simgrid
[simgrid.git] / examples / cpp / synchro-condition-variable / s4u-synchro-condition-variable.cpp
index a63fa62..b471b65 100644 (file)
@@ -1,22 +1,20 @@
-/* Copyright (c) 2006-2021. The SimGrid Team. All rights reserved.          */
+/* Copyright (c) 2006-2023. The SimGrid Team. All rights reserved.          */
 
 /* This program is free software; you can redistribute it and/or modify it
  * under the terms of the license (GNU LGPL) which comes with this package. */
 
-#include <mutex>           /* std::mutex and std::lock_guard */
+#include <mutex>           /* std::mutex and std::scoped_lock */
 #include <simgrid/s4u.hpp> /* All of S4U */
 
 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_test, "a sample log category");
+namespace sg4 = simgrid::s4u;
 
-std::string data;
-bool done = false;
-
-static void worker_fun(simgrid::s4u::ConditionVariablePtr cv, simgrid::s4u::MutexPtr mutex)
+static void worker_fun(sg4::ConditionVariablePtr cv, sg4::MutexPtr mutex, std::string& data, bool& done)
 {
-  std::unique_lock<simgrid::s4u::Mutex> lock(*mutex);
+  const std::scoped_lock lock(*mutex);
 
   XBT_INFO("Start processing data which is '%s'.", data.c_str());
-  data += std::string(" after processing");
+  data += " after processing";
 
   // Send data back to main()
   XBT_INFO("Signal to master that the data processing is completed, and exit.");
@@ -27,13 +25,16 @@ static void worker_fun(simgrid::s4u::ConditionVariablePtr cv, simgrid::s4u::Mute
 
 static void master_fun()
 {
-  auto mutex  = simgrid::s4u::Mutex::create();
-  auto cv     = simgrid::s4u::ConditionVariable::create();
-  data        = std::string("Example data");
-  auto worker = simgrid::s4u::Actor::create("worker", simgrid::s4u::Host::by_name("Jupiter"), worker_fun, cv, mutex);
+  auto mutex  = sg4::Mutex::create();
+  auto cv     = sg4::ConditionVariable::create();
+  std::string data = "Example data";
+  bool done        = false;
+
+  auto worker = sg4::Actor::create("worker", sg4::Host::by_name("Jupiter"), worker_fun, cv, mutex, std::ref(data),
+                                   std::ref(done));
 
   // wait for the worker
-  cv->wait(std::unique_lock<simgrid::s4u::Mutex>(*mutex), []() { return done; });
+  cv->wait(std::unique_lock(*mutex), [&done]() { return done; });
   XBT_INFO("data is now '%s'.", data.c_str());
 
   worker->join();
@@ -41,9 +42,9 @@ static void master_fun()
 
 int main(int argc, char** argv)
 {
-  simgrid::s4u::Engine e(&argc, argv);
+  sg4::Engine e(&argc, argv);
   e.load_platform("../../platforms/two_hosts.xml");
-  simgrid::s4u::Actor::create("main", simgrid::s4u::Host::by_name("Tremblay"), master_fun);
+  sg4::Actor::create("main", e.host_by_name("Tremblay"), master_fun);
   e.run();
 
   return 0;