Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
updated doc
[simgrid.git] / examples / cpp / synchro-condition-variable-waituntil / s4u-synchro-condition-variable-waituntil.cpp
index 493c794be2997c1dd6dfd4a226ce0793f2def0bd..0edd2ab68dbed82b9acd06c07790b29b3ac54be8 100644 (file)
@@ -1,4 +1,4 @@
-/* Copyright (c) 2006-2022. 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. */
@@ -7,17 +7,14 @@
 #include <simgrid/s4u.hpp> /* All of S4U */
 
 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_test, "a sample log category");
+namespace sg4 = simgrid::s4u;
 
-simgrid::s4u::MutexPtr mtx = nullptr;
-simgrid::s4u::ConditionVariablePtr cv = nullptr;
-bool ready = false;
-
-static void competitor(int id)
+static void competitor(int id, sg4::ConditionVariablePtr cv, sg4::MutexPtr mtx, std::shared_ptr<bool> ready)
 {
   XBT_INFO("Entering the race...");
-  std::unique_lock<simgrid::s4u::Mutex> lck(*mtx);
-  while (not ready) {
-    auto now = simgrid::s4u::Engine::get_clock();
+  std::unique_lock lck(*mtx);
+  while (not *ready) {
+    auto now = sg4::Engine::get_clock();
     if (cv->wait_until(lck, now + (id+1)*0.25) == std::cv_status::timeout) {
       XBT_INFO("Out of wait_until (timeout)");
     }
@@ -28,33 +25,34 @@ static void competitor(int id)
   XBT_INFO("Running!");
 }
 
-static void go()
+static void go(sg4::ConditionVariablePtr cv, sg4::MutexPtr mtx, std::shared_ptr<bool> ready)
 {
   XBT_INFO("Are you ready? ...");
-  simgrid::s4u::this_actor::sleep_for(3);
-  std::unique_lock<simgrid::s4u::Mutex> lck(*mtx);
+  sg4::this_actor::sleep_for(3);
+  std::unique_lock lck(*mtx);
   XBT_INFO("Go go go!");
-  ready = true;
+  *ready = true;
   cv->notify_all();
 }
 
 static void main_actor()
 {
-  mtx = simgrid::s4u::Mutex::create();
-  cv = simgrid::s4u::ConditionVariable::create();
+  auto mtx   = sg4::Mutex::create();
+  auto cv    = sg4::ConditionVariable::create();
+  auto ready = std::make_shared<bool>(false);
 
-  auto host = simgrid::s4u::this_actor::get_host();
+  auto host = sg4::this_actor::get_host();
   for (int i = 0; i < 10; ++i)
-    simgrid::s4u::Actor::create("competitor", host, competitor, i);
-  simgrid::s4u::Actor::create("go", host, go);
+    sg4::Actor::create("competitor", host, competitor, i, cv, mtx, ready);
+  sg4::Actor::create("go", host, go, cv, mtx, ready);
 }
 
 int main(int argc, char* argv[])
 {
-  simgrid::s4u::Engine e(&argc, argv);
+  sg4::Engine e(&argc, argv);
   e.load_platform("../../platforms/small_platform.xml");
 
-  simgrid::s4u::Actor::create("main", e.host_by_name("Tremblay"), main_actor);
+  sg4::Actor::create("main", e.host_by_name("Tremblay"), main_actor);
 
   e.run();
   return 0;