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