TaskPool.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #ifndef H_TASK_POOL_H
  2. #define H_TASK_POOL_H
  3. #include <list>
  4. #include "threadpp/threadpp.h"
  5. #include <cstdlib>
  6. #include <cstdio>
  7. namespace tq
  8. {
  9. template <typename TaskType>
  10. class TaskPool
  11. {
  12. public:
  13. TaskPool(unsigned capacity = 10);
  14. ~TaskPool();
  15. TaskType* GetTask(TaskType const& taskPrototype);
  16. void RecycleTask(TaskType* task);
  17. void Purge();
  18. private:
  19. threadpp::lock _mutex;
  20. std::list<TaskType*> _tasks;
  21. unsigned _capacity;
  22. };
  23. template <typename TaskType>
  24. TaskType* TaskPool<TaskType>::GetTask(TaskType const& taskPrototype)
  25. {
  26. _mutex.lock();
  27. if(!_tasks.empty())
  28. {
  29. TaskType* taskptr = _tasks.front();
  30. _tasks.pop_front();
  31. _mutex.unlock();
  32. new (taskptr)TaskType(taskPrototype);
  33. return taskptr;
  34. }
  35. else
  36. {
  37. _mutex.unlock();
  38. static int newcount = 0;
  39. TaskType* taskptr = new TaskType(taskPrototype);
  40. return taskptr;
  41. }
  42. }
  43. template <typename TaskType>
  44. void TaskPool<TaskType>::RecycleTask(TaskType* task)
  45. {
  46. (*task).~TaskType();
  47. _mutex.lock();
  48. if(_tasks.size()<_capacity)
  49. {
  50. _tasks.push_back(task);
  51. }
  52. else
  53. {
  54. free(task);
  55. }
  56. _mutex.unlock();
  57. }
  58. template <typename TaskType>
  59. void TaskPool<TaskType>::Purge()
  60. {
  61. _mutex.lock();
  62. if(!_tasks.empty())
  63. {
  64. for(typename std::list<TaskType*>::const_iterator it = _tasks.begin();it!=_tasks.end();++it)
  65. {
  66. free(*it);
  67. }
  68. _tasks.clear();
  69. }
  70. _mutex.unlock();
  71. }
  72. template <typename TaskType>
  73. TaskPool<TaskType>::TaskPool(unsigned capacity):
  74. _capacity(capacity)
  75. {
  76. }
  77. template <typename TaskType>
  78. TaskPool<TaskType>::~TaskPool()
  79. {
  80. this->Purge();
  81. }
  82. }
  83. #endif