C Plus Plus implement of a Async Queue, the capacity is not limited.
#include <mutex>
#include <condition_variable>
#include <queue>
/*
blocked task queue
if is empty, the getTask is blocked
TODO: limit the capcity of the queue
*/
template<class T>
class AsyncQueue: public std::queue<T>
{
public:
~AsyncQueue()
{
if(!m_stopped)
stop();
}
void addTask(const T &task)
{
std::unique_lock<std::mutex> lock(m_mutex);
this->push(task);
m_cvNotEmpty.notify_one();
}
//return false when stopped, else block until not empty
bool getTask(T &task)
{
std::unique_lock<std::mutex> lock(m_mutex);
while (this->empty())
{
m_cvNotEmpty.wait(lock);
if (m_stopped)
return false;
}
task = std::move(this->front());
this->pop();
return true;
}
// stop even queue is not empty
void stop()
{
m_stopped = true;
m_cvNotEmpty.notify_all();
}
private:
bool m_stopped{false};
std::mutex m_mutex;
std::condition_variable m_cvNotEmpty;
};