No puede seleccionar más de 25 temas
Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
|
- #pragma once
-
- #include <ecs/config.h>
-
- #include "./worker.h"
- #include "./types.h"
-
- beg_namespace_ecs_core_utils
- {
-
- struct thread_pool
- {
- private:
- using worker_vector = std::vector<thread_pool_worker>;
- using atomic_size_t = std::atomic<size_t>;
-
- private:
- task_queue _queue;
- worker_vector _workers;
- atomic_size_t _outstanding_inits;
-
- auto all_workers_finished() const noexcept
- {
- for (const auto& w : _workers)
- {
- if (!w.finished())
- {
- return false;
- }
- }
- return true;
- }
-
- inline void post_dummy_task()
- { post([]{ }); }
-
- void initialize_workers(size_t count)
- {
- _workers.reserve(count);
- for (size_t i = 0; i < count; ++i)
- {
- _workers.emplace_back(_queue);
- }
-
- _outstanding_inits = count;
- for (auto& w : _workers)
- {
- w.start(_outstanding_inits);
- }
- }
-
- public:
- inline thread_pool(size_t count)
- { initialize_workers(count); }
-
- ~thread_pool()
- {
- // wait for uninitialized workers
- while (_outstanding_inits > 0)
- {
- std::this_thread::sleep_for(std::chrono::milliseconds(50));
- }
-
- // stop all workers
- for (auto& w : _workers)
- {
- w.stop();
- }
-
- // post dummy tasks untill all workers has stopped
- while (!all_workers_finished())
- {
- post_dummy_task();
- }
-
- // join the worker threads
- for (auto& w : _workers)
- {
- w.join();
- }
- }
-
- template<typename T_func>
- inline void post(T_func&& func)
- { _queue.enqueue(std::forward<T_func>(func)); }
- };
-
- }
- end_namespace_ecs_core_utils
|