用c++11 写一个任务队列,支持模板的输入
#ifndef TASKQUEUE_H_
#define TASKQUEUE_H_
#include <stdio.h>
#include <list>
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <condition_variable>
template<typename T>
class TaskQueue {
public:
TaskQueue(int num)
{
_maxNum = num;
}
template<typename C>
void push_task(C&& task_func) {
{
std::lock_guard<std::mutex> lock(_mutex);
if (_queue.size() >= _maxNum)
{
// 丢弃
return;
}
_queue.emplace_back(std::forward<C>(task_func));
_condition.notify_one();
}
}
template<typename C>
void push_task_first(C&& task_func) {
{
std::lock_guard<std::mutex> lock(_mutex);
_queue.emplace_front(std::forward<C>(task_func));
_condition.notify_one();
}
}
bool get_task(T& tsk) {
std::unique_lock<std::mutex> lock(_mutex);
_condition.wait(lock, [&]()->bool { return !_queue.empty(); }); // suspend and wait ... //改成右值引用后性能提升了1倍多!
//tsk = std::move(_queue.front());
if (!_queue.empty())
{
tsk = _queue.front();
_queue.pop_front();
return true;
}
else
{
return false;
}
}
uint64_t size() {
//std::lock_guard<decltype(_mutex)> lock(_mutex);
std::lock_guard<std::mutex> lock(_mutex);
return _queue.size();
}
private:
std::list<T> _queue;
std::mutex _mutex;
std::condition_variable _condition;
int _maxNum;
};
// 一个延迟函数,可以随时退出
class TaskSleep
{
public:
void SleepMs(int64_t delayMs)
{
std::unique_lock<std::mutex> lock(_mutex);
_condition.wait_for(lock, std::chrono::milliseconds(delayMs), [&]()->bool {return !_queue.empty(); });
if (!_queue.empty())
{
_queue.pop_front();
}
}
void ExitSleep()
{
std::lock_guard<std::mutex> lock(_mutex);
_queue.push_back('a');
_condition.notify_one();
}
private:
std::mutex _mutex;
std::condition_variable _condition;
std::list<char> _queue;
};
#endif