7 #ifndef EMX_SAFETYQUEUE_HPP
8 #define EMX_SAFETYQUEUE_HPP
12 #include <condition_variable>
28 using OnCloned = std::function<T(
const T& data)>;
35 using OnFreed = std::function<void(T& data)>;
40 : m_total(total), m_clonedCb(clonedCb), m_freedCb(freedCb), m_exit(false) {
52 void Put(
const T& data) {
53 std::unique_lock<std::mutex> locker(m_mtx);
54 T clonedData = (m_clonedCb) ? m_clonedCb(data) : data;
55 if (clonedData ==
nullptr) {
58 m_queue.emplace_back(std::move(clonedData));
60 while ((
int)m_queue.size() > m_total) {
61 if (m_freedCb !=
nullptr) {
62 m_freedCb(m_queue.front());
68 if (!m_waitQueue.empty()) {
69 auto wait = m_waitQueue.front();
70 m_waitQueue.pop_front();
71 (*(wait.first)) =
false;
72 wait.second->notify_one();
83 std::unique_lock<std::mutex> locker(m_mtx);
84 while (m_queue.empty()) {
89 std::shared_ptr<bool> is_empty = std::make_shared<bool>(
true);
90 std::shared_ptr<std::condition_variable> cv = std::make_shared<std::condition_variable>();
91 m_waitQueue.emplace_back(std::make_pair(is_empty, cv));
92 cv->wait(locker, [is_empty,
this]() {
return !(*is_empty) || m_exit; });
95 if (m_exit && m_queue.empty()) {
98 T data = std::move(m_queue.front());
108 std::unique_lock<std::mutex> locker(m_mtx);
109 return m_queue.size();
116 std::unique_lock<std::mutex> locker(m_mtx);
117 if (m_freedCb !=
nullptr) {
118 for(
auto &data : m_queue) {
119 if (data !=
nullptr) {
132 std::unique_lock<std::mutex> locker(m_mtx);
135 for (
auto& wait : m_waitQueue) {
136 *(wait.first) =
false;
137 wait.second->notify_one();
147 std::unique_lock<std::mutex> locker(m_mtx);
154 std::list<T> m_queue;
155 std::list<std::pair<std::shared_ptr<bool>, std::shared_ptr<std::condition_variable>>> m_waitQueue;
158 std::atomic<bool> m_exit;
Definition: SafetyQueue.hpp:21
int Size()
获取队列长度
Definition: SafetyQueue.hpp:107
void Clear()
清除队列
Definition: SafetyQueue.hpp:115
void Stop()
优雅安全退出Get操作线程等待阻塞
Definition: SafetyQueue.hpp:131
void SetTotal(int total)
设置队列长度上限,默认为3
Definition: SafetyQueue.hpp:146
std::function< T(const T &data)> OnCloned
数据克隆
Definition: SafetyQueue.hpp:28
void Put(const T &data)
put数据到队列
Definition: SafetyQueue.hpp:52
std::function< void(T &data)> OnFreed
数据释放
Definition: SafetyQueue.hpp:35
T Get()
从队列中get数据
Definition: SafetyQueue.hpp:82
~SafetyQueue()
Definition: SafetyQueue.hpp:43
SafetyQueue(int total=3, OnCloned clonedCb=nullptr, OnFreed freedCb=nullptr)
Definition: SafetyQueue.hpp:37
Definition: EmxGpio.hpp:10