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;
};
本文介绍了如何使用C++实现一个无容量限制的异步队列,通过`std::queue`模板类,利用`std::mutex`和`std::condition_variable`实现线程安全,支持任务添加和获取功能,同时提供停止操作以控制队列行为。
322

被折叠的 条评论
为什么被折叠?



