#include "threadPool.h" ThreadPool::ThreadPool() : m_busyThreads{ 0 } , m_threads{std::vector(std::thread::hardware_concurrency())} , m_stopRequested{ false } { for (size_t i = 0; i < std::thread::hardware_concurrency(); ++i) { m_threads[i] = std::thread(ThreadWorker(this)); } } ThreadPool::~ThreadPool() { { std::lock_guard lock(m_mutex); m_stopRequested = true; m_condition_task.notify_all(); } for (size_t i = 0; i < m_threads.size(); ++i) { if (m_threads[i].joinable()) { m_threads[i].join(); } } } void ThreadPool::wait() { std::unique_lock lock(m_mutex); m_condition_finish.wait(lock, [this] { return m_tasks.empty() && m_busyThreads == 0; }); lock.unlock(); } ThreadWorker::ThreadWorker(ThreadPool* pool) : m_pool(pool) {} ThreadWorker::~ThreadWorker() {} void ThreadWorker::operator()() { std::unique_lock lock(m_pool->m_mutex); while (!m_pool->m_stopRequested || (m_pool->m_stopRequested && !m_pool->m_tasks.empty())) { m_pool->m_condition_task.wait(lock, [this] { return m_pool->m_stopRequested || !m_pool->m_tasks.empty(); }); if (!m_pool->m_tasks.empty()) { m_pool->m_busyThreads++; auto task = m_pool->m_tasks.front(); m_pool->m_tasks.pop(); lock.unlock(); task(); lock.lock(); m_pool->m_busyThreads--; m_pool->m_condition_finish.notify_one(); } } }