Logo AND Algorithmique Numérique Distribuée

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