task_queue.hpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include <atomic>
  2. #include <condition_variable>
  3. #include <functional>
  4. #include <mutex>
  5. #include <queue>
  6. #include <thread>
  7. /**
  8. * TaskQueue
  9. *
  10. * A task queue employs a pool of worker threads who can execute arbitrary tasks
  11. * @class
  12. */
  13. class TaskQueue {
  14. public:
  15. /**
  16. * @constructor
  17. * Nothing fancy
  18. */
  19. TaskQueue();
  20. /**
  21. * @destructor
  22. * Make sure all worker threads detach or join before destroying TaskQueue
  23. * instance
  24. */
  25. ~TaskQueue();
  26. /** PUBLIC METHODS **/
  27. /**
  28. * initialize
  29. *
  30. * To be called after an instance of TaskQueue is created.
  31. * @method
  32. */
  33. void initialize();
  34. /**
  35. * pushToQueue
  36. *
  37. * Add a task to the queue
  38. *
  39. * @method
  40. * @param[in] {std::function<void()>} A fully encapsulated template function
  41. * with its own internal state
  42. */
  43. void pushToQueue(std::function<void()> fn);
  44. private:
  45. /** PRIVATE METHODS **/
  46. /**
  47. * workerLoop
  48. *
  49. * The loop is the essential lifecycle of the worker
  50. * @method
  51. */
  52. void workerLoop();
  53. /**
  54. * deployWorkers
  55. *
  56. * Procures workers and sets them into existing by executing the workerLoop
  57. * function
  58. * @method
  59. */
  60. void deployWorkers();
  61. /**
  62. * detachThreads
  63. *
  64. * Allows threads to terminate.
  65. * @method
  66. * @cleanup
  67. */
  68. void detachThreads();
  69. /** PRIVATE MEMBERS **/
  70. /**
  71. * FIFO queue of templated function pointers
  72. */
  73. std::queue<std::function<void()>> m_task_queue;
  74. /**
  75. * vector of worker threads
  76. */
  77. std::vector<std::thread> m_thread_pool;
  78. /**
  79. * mutex for locking resources
  80. */
  81. std::mutex m_mutex_lock;
  82. /**
  83. * condition variable for controlling work execution
  84. */
  85. std::condition_variable pool_condition;
  86. /**
  87. * atomic boolean to ensure queue is handled in a thread-safe manner
  88. */
  89. std::atomic<bool> accepting_tasks;
  90. };