rogue
Loading...
Searching...
No Matches
Queue.h
Go to the documentation of this file.
1
17#ifndef __ROGUE_QUEUE_H__
18#define __ROGUE_QUEUE_H__
19#include "rogue/Directives.h"
20
21#include <stdint.h>
22
23#include <condition_variable>
24#include <mutex>
25#include <queue>
26
27namespace rogue {
37template <typename T>
38class Queue {
39 private:
40 std::queue<T> queue_;
41 mutable std::mutex mtx_;
42 std::condition_variable pushCond_;
43 std::condition_variable popCond_;
44 uint32_t max_;
45 uint32_t thold_;
46 bool busy_;
47 bool run_;
48
49 public:
52 max_ = 0;
53 thold_ = 0;
54 busy_ = false;
55 run_ = true;
56 }
57
61 void stop() {
62 std::unique_lock<std::mutex> lock(mtx_);
63 run_ = false;
64 pushCond_.notify_all();
65 popCond_.notify_all();
66 }
67
76 void setMax(uint32_t max) {
77 max_ = max;
78 }
79
84 void setThold(uint32_t thold) {
85 thold_ = thold;
86 }
87
92 void push(T const& data) {
93 std::unique_lock<std::mutex> lock(mtx_);
94
95 while (run_ && max_ > 0 && queue_.size() >= max_) pushCond_.wait(lock);
96
97 if (run_) queue_.push(data);
98 busy_ = (thold_ > 0 && queue_.size() >= thold_);
99 popCond_.notify_all();
100 }
101
106 bool empty() {
107 return queue_.empty();
108 }
109
114 uint32_t size() {
115 std::unique_lock<std::mutex> lock(mtx_);
116 return queue_.size();
117 }
118
123 bool busy() {
124 return busy_;
125 }
126
130 void reset() {
131 std::unique_lock<std::mutex> lock(mtx_);
132 while (!queue_.empty()) queue_.pop();
133 busy_ = false;
134 pushCond_.notify_all();
135 }
136
141 T pop() {
142 T ret;
143 std::unique_lock<std::mutex> lock(mtx_);
144 while (run_ && queue_.empty()) popCond_.wait(lock);
145 if (run_) {
146 ret = queue_.front();
147 queue_.pop();
148 }
149 busy_ = (thold_ > 0 && queue_.size() >= thold_);
150 pushCond_.notify_all();
151 return (ret);
152 }
153};
154} // namespace rogue
155
156#endif
Thread-safe bounded queue with optional busy threshold.
Definition Queue.h:38
bool empty()
Returns whether queue is currently empty.
Definition Queue.h:106
Queue()
Constructs an empty running queue.
Definition Queue.h:51
void reset()
Clears all queued entries and resets busy state.
Definition Queue.h:130
void push(T const &data)
Pushes one entry, blocking when queue is full.
Definition Queue.h:92
bool busy()
Returns busy state based on configured threshold.
Definition Queue.h:123
void setMax(uint32_t max)
Sets maximum queue depth before push() blocks.
Definition Queue.h:76
void setThold(uint32_t thold)
Sets busy-threshold depth used by busy().
Definition Queue.h:84
void stop()
Stops queue operation and wakes blocked producers/consumers.
Definition Queue.h:61
T pop()
Pops one entry, blocking until data is available or stopped.
Definition Queue.h:141
uint32_t size()
Returns current queue depth.
Definition Queue.h:114