#pragma once #include "scan_common.h" template class CTaskExecutor:public IService { public: CTaskExecutor(void); ~CTaskExecutor(void); enum TASK_STATE{ //没有任务 TASK_STATE_NOTASK, //任务已准备好,等待执行 TASK_STATE_TASK_READY, //任务执行中 TASK_STATE_EXCUTING, //任务完成中(保存结果) TASK_STATE_SAVING, //任务已经执行完成 TASK_STATE_COMPLETED, }; private : TASK_STATE m_task_state; TASK* m_task; TASK_RESULT * m_task_result; virtual ServiceState OnRunning( void ) { ServiceState nextState=IService::OnRunning(); if(nextState != running&& m_task_state ==TASK_STATE_NOTASK ) return nextState; switch(m_task_state){ case TASK_STATE_NOTASK: Sleep(10); break; case TASK_STATE_TASK_READY: m_task_state = TASK_STATE_EXCUTING; break; case TASK_STATE_EXCUTING: ExcuteTask(m_task,m_task_result); break; case TASK_STATE_SAVING: SaveTaskResult(m_task_result); break; case TASK_STATE_COMPLETED: break; } return running; } public: //添加任务 BOOL AddTask(TASK* task,TASK_RESULT * task_result){ if(m_task_state ==TASK_STATE_NOTASK){ m_task = task; m_task_result=task_result; m_task_state = TASK_STATE_TASK_READY; return TRUE; } return FALSE; } //执行任务 virtual BOOL ExcuteTask(TASK * task,TASK_RESULT * task_result); //执行任务 virtual void SaveTaskResult(TASK_RESULT * task_result); // 获取任务状态 TASK_STATE GetTaskState(){return m_task_state;} }; template class CTaskDispatcher { public: TaskExecutor m_TaskExecutors[EXECUTOR_COUNT]; TASK m_task_buffer[TASK_BUFFER_SIZE]; TASK_RESULT m_task_result_buffer[TASK_RESULT_BUFFER_SIZE]; CTaskDispatcher(void); ~CTaskDispatcher(void); private: int m_last_excutor_index; protected: void DispatchTask(TASK * task,TASK_RESULT * task_result,BOOL waite =TRUE){ BOOL retry = waite; do{ for(int i=0,excutor_index =m_last_excutor_index+1;i=EXECUTOR_COUNT)excutor_index =0; if(m_TaskExecutors[excutor_index].GetTaskState()==TASK_STATE_NOTASK){ BOOL success =m_TaskExecutors[excutor_index]. AddTask(task,task_result); if(success){ m_last_excutor_index = excutor_index; retry = FALSE; break; } } } if(retry)Sleep(10); }while(retry); } };