|
- #pragma once
-
- #include <thread>
- #include <ecs/config.h>
-
- #include "./types.h"
- #include "../movable_atomic.h"
-
- beg_namespace_ecs_core_utils
- {
-
- struct thread_pool_worker
- {
- private:
- enum class state
- {
- uninizialized,
- running,
- stopped,
- finished,
- };
-
- using atomic_state = movable_atomic<state>;
-
- std::thread _thread;
- task_queue& _queue;
- atomic_state _state;
-
- private:
- void run()
- {
- _state = state::running;
- while (_state == state::running)
- {
- task t;
- if (_queue.wait_dequeue_timed(t, std::chrono::milliseconds(500)))
- {
- t();
- }
- }
- _state = state::finished;
- }
-
- public:
- thread_pool_worker(task_queue& queue) noexcept
- : _queue(queue)
- { }
-
- thread_pool_worker(thread_pool_worker&&) = default;
- thread_pool_worker(const thread_pool_worker&) = delete;
-
- thread_pool_worker& operator=(thread_pool_worker&&) = default;
- thread_pool_worker& operator=(const thread_pool_worker&) = delete;
-
- template<typename T_counter>
- inline void start(T_counter& remaining_inits)
- {
- _thread = std::thread([this, &remaining_inits]{
- --remaining_inits;
- run();
- });
- }
-
- inline void stop() noexcept
- {
- assert(_state == state::running);
- _state = state::stopped;
- }
-
- inline void join() noexcept
- {
- assert(_thread.joinable());
- assert(_state == state::finished);
- _thread.join();
- }
-
- inline bool finished() const noexcept
- { return _state == state::finished; }
-
- };
-
- }
- end_namespace_ecs_core_utils
|