Logo AND Algorithmique Numérique Distribuée

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