ThreadTaskQueue.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //
  2. // ThreadTaskQueue.h
  3. // LibDriveRating-CXX
  4. //
  5. // Created by Melo Yao on 6/9/14.
  6. // Copyright (c) 2014 AutoNavi. All rights reserved.
  7. //
  8. #ifndef __LibDriveRating_CXX__ThreadTaskQueue__
  9. #define __LibDriveRating_CXX__ThreadTaskQueue__
  10. #include "TQInterface.h"
  11. #include "BaseTask.h"
  12. #include <list>
  13. #include <map>
  14. #include <vector>
  15. #include "threadpp/threadpp.h"
  16. namespace tq
  17. {
  18. class QueueRunnable;
  19. class ThreadTaskQueue:public IQueue
  20. {
  21. public:
  22. ThreadTaskQueue();
  23. void Start(unsigned int nThreads = 1);
  24. void Stop();
  25. bool IsStarted() const;
  26. void AddTask(ITask* task);//Will transfer the ownership of task.
  27. void GetTasks(ITask** tasksBuf, unsigned int taskBufSize) const;
  28. unsigned int TaskCount() const;
  29. void CancelAll();
  30. void WaitForFinish() ;
  31. void Suspend();
  32. void Resume();
  33. void SetTaskRecycler(TaskCategory cat, TaskRecycler recycler,void *context);
  34. void ClearTaskRecycler(TaskCategory cat);
  35. ~ThreadTaskQueue();
  36. protected:
  37. void LockQueue();
  38. void UnlockQueue();
  39. void NotifyQueue();
  40. ITask* NextTask();
  41. void FinishTask(ITask* task);
  42. friend class QueueRunnable;
  43. private:
  44. struct RecyclerPair
  45. {
  46. TaskRecycler recycler;
  47. void *context;
  48. RecyclerPair(TaskRecycler r,void* c):
  49. recycler(r),context(c)
  50. {
  51. }
  52. };
  53. std::map<TaskCategory,RecyclerPair> _recyclers;
  54. std::list<ITask*> _tasklist;
  55. std::vector<QueueRunnable*> _threads;
  56. threadpp::recursivelock _mutex;
  57. threadpp::lock _recyclerMutex;
  58. bool _started;
  59. bool _suspended;
  60. };
  61. }
  62. #endif /* defined(__LibDriveRating_CXX__ThreadTaskQueue__) */