RTC Toolkit  1.0.0
messageQueue.hpp
Go to the documentation of this file.
1 
12 #ifndef RTCTK_DATATASK_MESSAGEQUEUE_HPP
13 #define RTCTK_DATATASK_MESSAGEQUEUE_HPP
14 
15 #include <mutex>
16 #include <condition_variable>
17 #include <queue>
18 #include <optional>
19 
20 namespace rtctk::dataTask {
25 template <class T>
26 class MessageQueue {
27 public:
28 
29  inline void Post(T const& value) {
30  {
31  std::unique_lock<std::mutex> lock(m_mtx);
32  m_queue.push(value);
33  }
34  m_cv.notify_one();
35  }
36 
37  inline T Pend() {
38  std::unique_lock<std::mutex> lock(m_mtx);
39  m_cv.wait(lock, [&]{return not m_queue.empty();});
40  auto ret = m_queue.front();
41  m_queue.pop();
42  return ret;
43  }
44 
45  template <class Rep, class Period>
46  inline T Pend(std::chrono::duration<Rep, Period> timeout) {
47  std::unique_lock<std::mutex> lock(m_mtx);
48  auto to = m_cv.wait_for(lock, timeout, [&]{return not m_queue.empty();});
49  if(to == false) {
50  throw(std::runtime_error("MessageQueue.Pend() timed out"));
51  }
52  auto ret = m_queue.front();
53  m_queue.pop();
54  return ret;
55  }
56 
57  inline std::optional<T> TryPend() { // TODO: revisit naming
58  std::unique_lock<std::mutex> lock(m_mtx);
59  if(not m_queue.empty()) {
60  auto ret = m_queue.front();
61  m_queue.pop();
62  return ret;
63  }else {
64  return {};
65  }
66  }
67 
68  inline void Clear() {
69  std::unique_lock<std::mutex> lock(m_mtx);
70  while(not m_queue.empty()) {
71  m_queue.pop();
72  }
73  }
74 
75 private:
76  std::mutex m_mtx;
77  std::condition_variable m_cv;
78  std::queue<T> m_queue;
79 };
80 
81 } // namespace
82 
83 #endif
rtctk::dataTask::MessageQueue::Pend
T Pend(std::chrono::duration< Rep, Period > timeout)
Definition: messageQueue.hpp:46
rtctk::dataTask::MessageQueue::TryPend
std::optional< T > TryPend()
Definition: messageQueue.hpp:57
rtctk::dataTask::MessageQueue::Post
void Post(T const &value)
Definition: messageQueue.hpp:29
rtctk::dataTask
Definition: messageQueue.hpp:20
rtctk::dataTask::MessageQueue::Clear
void Clear()
Definition: messageQueue.hpp:68
rtctk::dataTask::MessageQueue
Definition: messageQueue.hpp:26
rtctk::dataTask::MessageQueue::Pend
T Pend()
Definition: messageQueue.hpp:37