Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Use C++17's std::scoped_lock where appropriate.
[simgrid.git] / examples / cpp / synchro-condition-variable-waituntil / s4u-synchro-condition-variable-waituntil.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::scoped_lock */
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 static void competitor(int id, sg4::ConditionVariablePtr cv, sg4::MutexPtr mtx, std::shared_ptr<bool> ready)
13 {
14   XBT_INFO("Entering the race...");
15   std::unique_lock lock(*mtx);
16   while (not *ready) {
17     auto now = sg4::Engine::get_clock();
18     if (cv->wait_until(lock, now + (id + 1) * 0.25) == std::cv_status::timeout) {
19       XBT_INFO("Out of wait_until (timeout)");
20     } else {
21       XBT_INFO("Out of wait_until (YAY!)");
22     }
23   }
24   XBT_INFO("Running!");
25 }
26
27 static void go(sg4::ConditionVariablePtr cv, sg4::MutexPtr mtx, std::shared_ptr<bool> ready)
28 {
29   XBT_INFO("Are you ready? ...");
30   sg4::this_actor::sleep_for(3);
31   const std::scoped_lock lock(*mtx);
32   XBT_INFO("Go go go!");
33   *ready = true;
34   cv->notify_all();
35 }
36
37 static void main_actor()
38 {
39   auto mtx   = sg4::Mutex::create();
40   auto cv    = sg4::ConditionVariable::create();
41   auto ready = std::make_shared<bool>(false);
42
43   auto host = sg4::this_actor::get_host();
44   for (int i = 0; i < 10; ++i)
45     sg4::Actor::create("competitor", host, competitor, i, cv, mtx, ready);
46   sg4::Actor::create("go", host, go, cv, mtx, ready);
47 }
48
49 int main(int argc, char* argv[])
50 {
51   sg4::Engine e(&argc, argv);
52   e.load_platform("../../platforms/small_platform.xml");
53
54   sg4::Actor::create("main", e.host_by_name("Tremblay"), main_actor);
55
56   e.run();
57   return 0;
58 }