22 #ifndef SINGA_UTILS_SAFE_QUEUE_H_ 23 #define SINGA_UTILS_SAFE_QUEUE_H_ 29 #include <condition_variable> 35 template <
typename T,
class Container = std::queue<T>>
40 std::lock_guard<std::mutex> lock(mutex_);
48 std::lock_guard<std::mutex> lock(mutex_);
50 condition_.notify_one();
59 std::unique_lock<std::mutex> lock(mutex_);
60 condition_.wait(lock, [
this]() {
return !queue_.empty(); });
68 bool Pop(T& item, std::uint64_t timeout) {
69 std::unique_lock<std::mutex> lock(mutex_);
75 if (condition_.wait_for(lock, std::chrono::microseconds(timeout))
76 == std::cv_status::timeout)
80 item = queue_.front();
90 std::unique_lock<std::mutex> lock(mutex_);
105 std::lock_guard<std::mutex> lock(mutex_);
106 return queue_.size();
111 mutable std::mutex mutex_;
112 std::condition_variable condition_;
127 bool Push(
const T& e,
int priority) {
130 ele.priority = priority;
150 bool Pop(T& e, std::uint64_t timeout) {
152 if (queue_.pop(ele, timeout)) {
166 if (queue_.TryPop(ele)) {
178 return queue_.Size();
185 inline bool operator<(
const Element &other)
const {
186 return priority < other.priority;
193 #endif // SINGA_UTILS_SAFE_QUEUE_H_ bool TryPop(T &e)
Try to pop an element from the queue.
Definition: safe_queue.h:89
bool Push(const T &e)
Push an element into the queue.
Definition: safe_queue.h:47
bool Pop(T &e, std::uint64_t timeout)
Pop the item with the highest priority from the queue until one element is poped or timeout...
Definition: safe_queue.h:150
bool Push(const T &e, int priority)
Push an element into the queue with a given priority.
Definition: safe_queue.h:127
unsigned int Size() const
Definition: safe_queue.h:177
Thread safe priority queue.
Definition: safe_queue.h:119
unsigned int Size() const
Definition: safe_queue.h:104
void Pop(T &e)
Pop an element from the queue.
Definition: safe_queue.h:58
void Pop(T &e)
Pop an element from the queue with the highest priority.
Definition: safe_queue.h:139
Thread-safe queue.
Definition: safe_queue.h:36
bool Pop(T &item, std::uint64_t timeout)
Pop an item from the queue until one element is poped or timout.
Definition: safe_queue.h:68
bool TryPop(T &e)
Try to pop an element from the queue.
Definition: safe_queue.h:164