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 <atomic>
24#include <condition_variable>
25#include <mutex>
26#include <queue>
27
28namespace rogue {
38template <typename T>
39class Queue {
40 private:
41 std::queue<T> queue_;
42 mutable std::mutex mtx_;
43 std::condition_variable pushCond_;
44 std::condition_variable popCond_;
45 uint32_t max_ = 0;
46 uint32_t thold_ = 0;
47 std::atomic<bool> busy_{false};
48 bool run_ = true;
49
50 public:
52 Queue() = default;
53
57 void stop() {
58 std::unique_lock<std::mutex> lock(mtx_);
59 run_ = false;
60 pushCond_.notify_all();
61 popCond_.notify_all();
62 }
63
72 void setMax(uint32_t max) {
73 max_ = max;
74 }
75
80 void setThold(uint32_t thold) {
81 thold_ = thold;
82 }
83
88 void push(T const& data) {
89 std::unique_lock<std::mutex> lock(mtx_);
90
91 while (run_ && max_ > 0 && queue_.size() >= max_) pushCond_.wait(lock);
92
93 if (run_) queue_.push(data);
94 busy_ = (thold_ > 0 && queue_.size() >= thold_);
95 popCond_.notify_all();
96 }
97
102 bool empty() {
103 return queue_.empty();
104 }
105
110 uint32_t size() {
111 std::unique_lock<std::mutex> lock(mtx_);
112 return queue_.size();
113 }
114
119 bool busy() {
120 return busy_;
121 }
122
126 void reset() {
127 std::unique_lock<std::mutex> lock(mtx_);
128 while (!queue_.empty()) queue_.pop();
129 busy_ = false;
130 pushCond_.notify_all();
131 }
132
137 T pop() {
138 T ret;
139 std::unique_lock<std::mutex> lock(mtx_);
140 while (run_ && queue_.empty()) popCond_.wait(lock);
141 if (run_) {
142 ret = queue_.front();
143 queue_.pop();
144 }
145 busy_ = (thold_ > 0 && queue_.size() >= thold_);
146 pushCond_.notify_all();
147 return (ret);
148 }
149};
150} // namespace rogue
151
152#endif
Thread-safe bounded queue with optional busy threshold.
Definition Queue.h:39
bool empty()
Returns whether queue is currently empty.
Definition Queue.h:102
void reset()
Clears all queued entries and resets busy state.
Definition Queue.h:126
void push(T const &data)
Pushes one entry, blocking when queue is full.
Definition Queue.h:88
bool busy()
Returns busy state based on configured threshold.
Definition Queue.h:119
void setMax(uint32_t max)
Sets maximum queue depth before push() blocks.
Definition Queue.h:72
void setThold(uint32_t thold)
Sets busy-threshold depth used by busy().
Definition Queue.h:80
void stop()
Stops queue operation and wakes blocked producers/consumers.
Definition Queue.h:57
T pop()
Pops one entry, blocking until data is available or stopped.
Definition Queue.h:137
Queue()=default
Constructs an empty running queue.
uint32_t size()
Returns current queue depth.
Definition Queue.h:110