#include "thread_pool.h" #include #include #include namespace threading { ThreadPool::ThreadPool() { size_t const thread_count{ std::max(std::thread::hardware_concurrency() - 1, 1u) }; this->threads.reserve(thread_count); for (size_t i{ 0 }; i < thread_count; ++i) { this->threads.emplace_back(std::bind(&ThreadPool::ThreadFn, this)); } } ThreadPool::~ThreadPool() { { std::scoped_lock lock{ this->lock }; this->shutdown = true; this->threadNotifier.notify_all(); } for (std::thread &thread : this->threads) { thread.join(); } } size_t ThreadPool::GetThreadCount() { return this->threads.size(); } void ThreadPool::ScheduleTask(TaskFunc fn) { std::scoped_lock lock{ this->lock }; this->taskQueue.emplace(std::move(fn)); this->threadNotifier.notify_one(); } void ThreadPool::ThreadFn() { TaskFunc function; for(;;) { { std::unique_lock lock{ this->lock }; while (!this->shutdown && this->taskQueue.empty()) { this->threadNotifier.wait(lock); } if (this->taskQueue.empty()) { return; } function = std::move(this->taskQueue.front()); this->taskQueue.pop(); } function.operator()(); } } ThreadPool tasks{}; }