任务处理器(Processor.h):
#pragma once
#include <deque>
#include "Thread.h"
#include "Synchronized.h"
#include "Task.h"
class Processor : public Thread
{
protected:
// 处理器是否运行
bool _running;
// 任务队列
std::deque<Task*> _queue;
// 同步锁
Synchronized _syncObject;
public:
// 构造函数
Processor(): _running(false){ }
// 析构函数
virtual ~Processor(){clear();}
void enqueue(Task* task)
{
_syncObject.lock();
_queue.push_back(task);
_syncObject.notify();
_syncObject.unlock();
}
void stop()
{
_syncObject.lock();
_running = false;
_syncObject.unlock();
::Sleep(500);
}
void clear()
{
_syncObject.lock();
std::deque<Task*>::iterator it = _queue.begin();
while (it != _queue.end())
{
delete (*it);
++it;
}
_queue.clear();
_syncObject.unlock();
}
public:
virtual void run()
{
// 线程里面有COM对象操作
CoInitializeEx( NULL, COINIT_MULTITHREADED );
_running = true;
while (_running)
{
Sleep(1);
Task* task = take();
if(task != NULL)
{
bool complete = task->execute();
if(complete == false)
{
// 任务执行失败了,重新压入队列
Sleep(50);
enqueue(task);
}
else
{
delete task;
}
}
}
// 处理器退出,清空任务列表
clear();
CoUninitialize();
}
protected:
// 从队列获取任务
Task* take()
{
Task* task = NULL;
_syncObject.lock();
while (_queue.empty() && _running)
{
_syncObject.wait(10);
}
if (_running)
{
task = _queue.front();
_queue.pop_front();
}
_syncObject.unlock();
return task;
}
bool isEmpty()
{
_syncObject.lock();
bool ret = _queue.empty();
_syncObject.unlock();
return ret;
}
};