Callisto Engine
blocking_queue.h
1#pragma once
2#include <condition_variable>
3#include <deque>
4#include <mutex>
5#include "../api_status.h"
6
7namespace cl::threading {
19 template <typename T>
21 private:
22 bool closed {false};
23 std::condition_variable cond;
24 std::deque<T> q;
25 std::mutex mtx;
26
27 public:
32 void push(T&& item) {
33 // Add the item to the queue under a mutex lock
34 {
35 std::lock_guard<std::mutex> lock{ mtx };
36 q.push_front(std::move(item));
37 }
38
39 cond.notify_one();
40 }
41
54 cl::api_status pop(T* next) {
55 // Grab the lock and wait for the condvar to receive a notification
56 std::unique_lock<std::mutex> lock{ mtx };
57 this->cond.wait(lock, [this](){
58 return closed || !this->q.empty();
59 });
60
61 // If the queue has been closed, stop pulling values
62 if (closed) {
63 return api_status::no_result;
64 }
65
66 // Once we get the signal, pop an item from the queue
67 *next = std::move(q.back());
68 q.pop_back();
69 return api_status::ok;
70 }
71
76 size_t workload_count() const {
77 return q.size();
78 }
79
88 void close() {
89 // Set the closed flag and wake up the thread
90 {
91 std::lock_guard<std::mutex> lock{ mtx };
92 closed = true;
93 }
94
95 // Unblock the thread
96 cond.notify_one();
97 }
98 };
99}
A thread-safe blocking concurrent queue.
Definition: blocking_queue.h:20
size_t workload_count() const
Returns the current workload count.
Definition: blocking_queue.h:76
void close()
close the queue
Definition: blocking_queue.h:88
cl::api_status pop(T *next)
Pops an item from the queue.
Definition: blocking_queue.h:54
void push(T &&item)
Pushes a new item to the queue, under a lock.
Definition: blocking_queue.h:32