Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

86 linhas
2.1 KiB

  1. #pragma once
  2. #include <ecs/core/utils/thread_pool/worker.h>
  3. #include <ecs/core/utils/thread_pool/task_queue.inl>
  4. namespace ecs {
  5. namespace core {
  6. namespace utils {
  7. inline thread_pool_worker
  8. ::thread_pool_worker(concurrent_task_queue& all_tasks, size_t thread_id) noexcept
  9. : _all_tasks(all_tasks)
  10. , _thread_id(thread_id)
  11. { }
  12. template<typename T_rep, typename T_period>
  13. inline bool thread_pool_worker
  14. ::pop(task& t, const std::chrono::duration<T_rep, T_period>& timeout)
  15. {
  16. std::unique_lock<std::mutex> lock(_mutex);
  17. do
  18. {
  19. if (_state != state::running)
  20. {
  21. return false;
  22. }
  23. if (!_own_tasks.empty())
  24. {
  25. t = std::move(_own_tasks.front());
  26. _own_tasks.pop();
  27. return true;
  28. }
  29. if (!_all_tasks.empty() && _all_tasks.pop(t)) // TODO: this will sometimes return false, even if the queue is not yet empty
  30. {
  31. return true;
  32. }
  33. } while(_conditional.wait_for(lock, timeout) != std::cv_status::timeout);
  34. return false;
  35. }
  36. template<typename T_counter>
  37. inline void thread_pool_worker
  38. ::start(T_counter& remaining_inits)
  39. {
  40. _thread = std::thread([this, &remaining_inits]{
  41. --remaining_inits;
  42. run();
  43. });
  44. }
  45. inline void thread_pool_worker
  46. ::stop() noexcept
  47. {
  48. assert(_state == state::running);
  49. _state = state::stopped;
  50. }
  51. inline void thread_pool_worker
  52. ::join() noexcept
  53. {
  54. assert(_thread.joinable());
  55. _thread.join();
  56. }
  57. inline bool thread_pool_worker
  58. ::finished() const noexcept
  59. {
  60. return _state == state::finished;
  61. }
  62. template<typename T_task>
  63. inline void thread_pool_worker
  64. ::post(T_task&& task)
  65. {
  66. std::unique_lock<std::mutex> lock(_mutex);
  67. _own_tasks.emplace(std::forward<T_task>(task));
  68. signal();
  69. }
  70. inline void thread_pool_worker
  71. ::signal()
  72. {
  73. _conditional.notify_all();
  74. }
  75. } } }