ILLIXR: Illinois Extended Reality Testbed
stoplight.hpp
1 #pragma once
2 
3 #include "phonebook.hpp"
4 
5 #include <atomic>
6 #include <condition_variable>
7 #include <mutex>
8 
9 namespace ILLIXR {
10 
16 class Event {
17 private:
18  mutable std::mutex _m_mutex;
19  mutable std::condition_variable _m_cv;
20  std::atomic<bool> _m_value = false;
21 
22 public:
28  void set(bool new_value = true) {
29  {
30  std::lock_guard lock{_m_mutex};
31  _m_value = new_value;
32  }
33  if (new_value) {
34  _m_cv.notify_all();
35  }
36  }
37 
41  void clear() {
42  set(false);
43  }
44 
48  bool is_set() const {
49  return _m_value;
50  }
51 
55  void wait() const {
56  std::unique_lock<std::mutex> lock{_m_mutex};
57  // Check if we even need to wait
58  if (_m_value) {
59  return;
60  }
61  _m_cv.wait(lock, [this] {
62  return _m_value.load();
63  });
64  }
65 
71  template<class Clock, class Rep, class Period>
72  bool wait_timeout(const std::chrono::duration<Rep, Period>& duration) const {
73  auto timeout_time = Clock::now() + duration;
74  if (_m_value) {
75  return true;
76  }
77  std::unique_lock<std::mutex> lock{_m_mutex};
78  while (_m_cv.wait_until(lock, timeout_time) != std::cv_status::timeout) {
79  if (_m_value) {
80  return true;
81  }
82  }
83  return false;
84  }
85 };
86 
107 public:
108  void wait_for_ready() const {
109  _m_ready.wait();
110  }
111 
112  void signal_ready() {
113  _m_ready.set();
114  }
115 
116  bool check_should_stop() const {
117  return _m_should_stop.is_set();
118  }
119 
120  void signal_should_stop() {
121  _m_should_stop.set();
122  }
123 
124  void wait_for_shutdown_complete() const {
125  _m_shutdown_complete.wait();
126  }
127 
128  bool check_shutdown_complete() const {
129  return _m_shutdown_complete.is_set();
130  }
131 
132  void signal_shutdown_complete() {
133  _m_shutdown_complete.set();
134  }
135 
136 private:
137  Event _m_ready;
138  Event _m_should_stop;
139  Event _m_shutdown_complete;
140 };
141 
142 } // namespace ILLIXR
A boolean condition-variable.
Definition: stoplight.hpp:16
void clear()
Clears the condition-variable.
Definition: stoplight.hpp:41
bool wait_timeout(const std::chrono::duration< Rep, Period > &duration) const
Wait for the event to be set with a timeout.
Definition: stoplight.hpp:72
void set(bool new_value=true)
Sets the condition-variable to new_value.
Definition: stoplight.hpp:28
void wait() const
Wait indefinitely for the event to be set.
Definition: stoplight.hpp:55
bool is_set() const
Test if is set without blocking.
Definition: stoplight.hpp:48
Start/stop synchronization for the whole application.
Definition: stoplight.hpp:106
A 'service' that can be registered in the phonebook.
Definition: phonebook.hpp:86
RAC_ERRNO_MSG.
Definition: data_format.hpp:15