VC++ 任务队列(任务处理器)

任务处理器(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;
	}

};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值