TaskDispatcher.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #pragma once
  2. #include "scan_common.h"
  3. template<class TASK,class TASK_RESULT> class CTaskExecutor:public IService
  4. {
  5. public:
  6. CTaskExecutor(void);
  7. ~CTaskExecutor(void);
  8. enum TASK_STATE{
  9. //没有任务
  10. TASK_STATE_NOTASK,
  11. //任务已准备好,等待执行
  12. TASK_STATE_TASK_READY,
  13. //任务执行中
  14. TASK_STATE_EXCUTING,
  15. //任务完成中(保存结果)
  16. TASK_STATE_SAVING,
  17. //任务已经执行完成
  18. TASK_STATE_COMPLETED,
  19. };
  20. private :
  21. TASK_STATE m_task_state;
  22. TASK* m_task;
  23. TASK_RESULT * m_task_result;
  24. virtual ServiceState OnRunning( void )
  25. {
  26. ServiceState nextState=IService::OnRunning();
  27. if(nextState != running&& m_task_state ==TASK_STATE_NOTASK ) return nextState;
  28. switch(m_task_state){
  29. case TASK_STATE_NOTASK:
  30. Sleep(10);
  31. break;
  32. case TASK_STATE_TASK_READY:
  33. m_task_state = TASK_STATE_EXCUTING;
  34. break;
  35. case TASK_STATE_EXCUTING:
  36. ExcuteTask(m_task,m_task_result);
  37. break;
  38. case TASK_STATE_SAVING:
  39. SaveTaskResult(m_task_result);
  40. break;
  41. case TASK_STATE_COMPLETED:
  42. break;
  43. }
  44. return running;
  45. }
  46. public:
  47. //添加任务
  48. BOOL AddTask(TASK* task,TASK_RESULT * task_result){
  49. if(m_task_state ==TASK_STATE_NOTASK){
  50. m_task = task;
  51. m_task_result=task_result;
  52. m_task_state = TASK_STATE_TASK_READY;
  53. return TRUE;
  54. }
  55. return FALSE;
  56. }
  57. //执行任务
  58. virtual BOOL ExcuteTask(TASK * task,TASK_RESULT * task_result);
  59. //执行任务
  60. virtual void SaveTaskResult(TASK_RESULT * task_result);
  61. // 获取任务状态
  62. TASK_STATE GetTaskState(){return m_task_state;}
  63. };
  64. template<class TaskExecutor,class TASK ,class TASK_RESULT ,int EXECUTOR_COUNT,int TASK_BUFFER_SIZE ,int TASK_RESULT_BUFFER_SIZE > class CTaskDispatcher
  65. {
  66. public:
  67. TaskExecutor m_TaskExecutors[EXECUTOR_COUNT];
  68. TASK m_task_buffer[TASK_BUFFER_SIZE];
  69. TASK_RESULT m_task_result_buffer[TASK_RESULT_BUFFER_SIZE];
  70. CTaskDispatcher(void);
  71. ~CTaskDispatcher(void);
  72. private:
  73. int m_last_excutor_index;
  74. protected:
  75. void DispatchTask(TASK * task,TASK_RESULT * task_result,BOOL waite =TRUE){
  76. BOOL retry = waite;
  77. do{
  78. for(int i=0,excutor_index =m_last_excutor_index+1;i<EXECUTOR_COUNT;i++,excutor_index++){
  79. if(excutor_index>=EXECUTOR_COUNT)excutor_index =0;
  80. if(m_TaskExecutors[excutor_index].GetTaskState()==TASK_STATE_NOTASK){
  81. BOOL success =m_TaskExecutors[excutor_index]. AddTask(task,task_result);
  82. if(success){
  83. m_last_excutor_index = excutor_index;
  84. retry = FALSE;
  85. break;
  86. }
  87. }
  88. }
  89. if(retry)Sleep(10);
  90. }while(retry);
  91. }
  92. };