Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

83 строки
1.9 KiB

  1. #pragma once
  2. #include <thread>
  3. #include <ecs/config.h>
  4. #include "./types.h"
  5. #include "../movable_atomic.h"
  6. beg_namespace_ecs_core_utils
  7. {
  8. struct thread_pool_worker
  9. {
  10. private:
  11. enum class state
  12. {
  13. uninizialized,
  14. running,
  15. stopped,
  16. finished,
  17. };
  18. using atomic_state = movable_atomic<state>;
  19. std::thread _thread;
  20. task_queue& _queue;
  21. atomic_state _state;
  22. private:
  23. void run()
  24. {
  25. _state = state::running;
  26. while (_state == state::running)
  27. {
  28. task t;
  29. if (_queue.wait_dequeue_timed(t, std::chrono::milliseconds(500)))
  30. {
  31. t();
  32. }
  33. }
  34. _state = state::finished;
  35. }
  36. public:
  37. thread_pool_worker(task_queue& queue) noexcept
  38. : _queue(queue)
  39. { }
  40. thread_pool_worker(thread_pool_worker&&) = default;
  41. thread_pool_worker(const thread_pool_worker&) = delete;
  42. thread_pool_worker& operator=(thread_pool_worker&&) = default;
  43. thread_pool_worker& operator=(const thread_pool_worker&) = delete;
  44. template<typename T_counter>
  45. inline void start(T_counter& remaining_inits)
  46. {
  47. _thread = std::thread([this, &remaining_inits]{
  48. --remaining_inits;
  49. run();
  50. });
  51. }
  52. inline void stop() noexcept
  53. {
  54. assert(_state == state::running);
  55. _state = state::stopped;
  56. }
  57. inline void join() noexcept
  58. {
  59. assert(_thread.joinable());
  60. assert(_state == state::finished);
  61. _thread.join();
  62. }
  63. inline bool finished() const noexcept
  64. { return _state == state::finished; }
  65. };
  66. }
  67. end_namespace_ecs_core_utils