#include "StdAfx.h"
|
#include "ThreadPool.h"
|
|
ThreadPool::ThreadPool(size_t thread_count) : m_stop(false) {
|
for (size_t i = 0; i < thread_count; ++i) {
|
m_threads.emplace_back(&ThreadPool::worker_thread, this);
|
}
|
}
|
|
ThreadPool::~ThreadPool() {
|
{
|
std::unique_lock<std::mutex> lock(m_queue_mutex);
|
m_stop = true;
|
}
|
m_cv.notify_all();
|
for (std::thread& worker : m_threads) {
|
if (worker.joinable()) {
|
worker.join();
|
}
|
}
|
}
|
|
void ThreadPool::worker_thread() {
|
while (true) {
|
std::function<void()> task;
|
{
|
std::unique_lock<std::mutex> lock(m_queue_mutex);
|
m_cv.wait(lock, [this]() { return m_stop || !m_tasks.empty(); });
|
if (m_stop && m_tasks.empty()) {
|
return;
|
}
|
task = std::move(m_tasks.front());
|
m_tasks.pop();
|
}
|
task();
|
}
|
}
|