TermOx
listener_thread.hpp
1 #ifndef TERMOX_COMMON_LISTENER_THREAD_HPP
2 #define TERMOX_COMMON_LISTENER_THREAD_HPP
3 #include <cassert>
4 #include <condition_variable>
5 #include <future>
6 #include <mutex>
7 #include <utility>
8 
9 namespace ox {
10 
12 
15 template <typename Function_t>
17  public:
19 
21  Listener_thread(Function_t&& action)
22  : action_{std::forward<Function_t>(action)}
23  {}
24 
27  {
28  this->exit();
29  this->wait();
30  }
31 
32  public:
34  void launch()
35  {
36  assert(!fut_.valid());
37  fut_ = std::async(std::launch::async, [this] {
38  exit_ = false;
39  notify_ = false;
40  auto lock = std::unique_lock{mtx_};
41  while (true) {
42  cv_.wait(lock, [this] { return notify_ || exit_; });
43  if (notify_) {
44  action_();
45  notify_ = false;
46  }
47  if (exit_) {
48  exit_ = false;
49  break;
50  }
51  }
52  });
53  }
54 
56  void notify()
57  {
58  {
59  auto const lock = std::lock_guard{mtx_};
60  notify_ = true;
61  }
62  cv_.notify_one();
63  }
64 
66  void exit()
67  {
68  {
69  auto const lock = std::lock_guard{mtx_};
70  exit_ = true;
71  }
72  cv_.notify_one();
73  }
74 
76  void wait()
77  {
78  fut_.wait();
79  if (fut_.valid())
80  fut_.get();
81  }
82 
83  private:
84  bool exit_ = false;
85  bool notify_ = false;
86  Function_t action_;
87  std::mutex mtx_;
88  std::condition_variable cv_;
89  std::future<void> fut_;
90 };
91 
92 } // namespace ox
93 #endif // TERMOX_COMMON_LISTENER_THREAD_HPP
Thread that waits to be notified, then performs some action.
Definition: listener_thread.hpp:16
void notify()
Wakes up the thread and has it run the action once.
Definition: listener_thread.hpp:56
~Listener_thread()
Shutdown the listener thread.
Definition: listener_thread.hpp:26
void exit()
Notify the thread to exit.
Definition: listener_thread.hpp:66
void wait()
Blocks until the thread is dead.
Definition: listener_thread.hpp:76
Listener_thread(Function_t &&action)
Launch the listener thread.
Definition: listener_thread.hpp:21
void launch()
Start the thread that will wait for notification.
Definition: listener_thread.hpp:34