Logo AND Algorithmique Numérique Distribuée

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